douzhe2981 2014-10-25 00:55
浏览 9
已采纳

根据出现情况替换字符串中的符号。 PHP

I have a string that is formatted by symbols (symbols similar to those used to format questions on this site).

Rules:

  1. **Hello** means bold = < b>Hello< /b>

  2. *Hello\\ means bulleted list = < li>Hello< /li>

  3. Hello\\ means line break = Hello< br>

I want to replace:

  1. Every first occurence of ** with < b> and every second ** with < /b>.
  2. The same for * with < li> and \\ with < /li>.
  3. All \\ that occur without a * somewhere in the string before, should be converted to < br>.

Example string:

$myString = 'Hello my **Friend**,\\here is the stuff you need to buy for me:*knife\\*water bottle\\***fake ID**\\\\\\Thank you in advance and don not forget the **fake ID**!\\Sincerely yours\\Eddy'

Note: This style is not my invention. It is in use and I have to convert it.

I preg_match()-ed parts of it to get the stuff between the tags.

$myString = 'Hello my **Friend**,\\here is the stuff you need to buy for me:*knife\\*water bottle\\***fake ID**\\\\\\Thank you in advance and don not forget the **fake ID**!\\Sincerely yours\\Eddy';
        $result = array();
        $firstBold = '<b>'. preg_match('~\*\*(.*?)\*\*~', $myString, $firstBold) . </b>; 
        $result +=  $firstBold 
        // and so on...

(Ignore mistakes in this, its written from memory)

I didn't consider the words before the first bold, but it's basically the same. This will get the job done at the end but it seems cumbersome to me. I am in search for a more elegant way to do this.

What is the best way to solve this in PHP?

  • 写回答

1条回答 默认 最新

  • dongyan1491 2014-10-25 03:09
    关注

    You can use preg_replace. because of your markup your order of replacement will matter.

    http://php.net/manual/en/function.preg-replace.php

     $myString = preg_replace("/[*][*]([^*]+)[*][*]/",'<b>${1}</b>',$myString);
     $myString = preg_replace("/[*]([^\/]+)[\/][\/]/",'<li>${1}</li>',$myString);
     $myString = str_replace("//",'<br/>',$myString);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 从Freecad中宏下载的DesignSPHysics,出现如下问题是什么原因导致的(语言-python)
  • ¥30 notepad++ 自定义代码补全提示
  • ¥15 MATLAB有限差分法解一维边值问题
  • ¥200 内网渗透测试 横向渗透 Windows漏洞 Windows权限维持
  • ¥15 数据结构图的相关代码实现
  • ¥15 python中aiohttp.client_exceptions.ContentTypeError
  • ¥30 DeepLung肺结节检测生成最大froc值对应的epoch报错
  • ¥15 信号发生器如何将频率调大,步尽值改成10
  • ¥15 keil 5 编程智能家具,风扇台灯开关,人体感应等
  • ¥100 找一名渗透方面的专家