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


Replace symbols in string dependent on occurence. PHP

我有一个用符号格式化的字符串(符号类似于本网站上用来格式化问题的符号)。

规则:

  1. **Hello**表示粗体=<b> 你好<b>

  2. *Hello''''表示项目符号列表=<li>你好<li>

  3. Hello''''表示换行=Hello<br>

我想替换:

  1. 带有<b> 并且每秒钟**具有<b>
  2. 对于*<li>和''''with<li>
  3. 所有之前字符串中不带*的''''都应转换为<br>

示例字符串:

$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'

注意:这种风格不是我的发明。它正在使用中,我必须转换它。

我预处理了它的一部分,以获得标签之间的内容。

$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...

(忽略其中的错误,它是从内存中写入的)

我没有考虑第一个粗体之前的单词,但基本上是一样的。这最终会完成工作,但对我来说似乎很麻烦。我正在寻找一种更优雅的方式来完成这项工作。

在PHP中解决此问题的最佳方法是什么

您可以使用preg_replace。由于您的加价,您的更换订单将很重要。

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);