preg_match_all和preg_replace foreach循环

时间:2016-01-25 06:47:47

标签: php regex

我正在尝试将[quote =“author”] text [/ quote]转换为格式化的div块。

$p_text

[quote="person1"]Hello![/quote]
[quote="person2"]Hi![/quote]

功能:

function bbCode($p_text){

      $pattern = '/\[quote="(.+?)"\]/'; // matches the author name, i.e. person1
      preg_match_all($pattern, $p_text, $matches);

      $authorCounter = 0;

      foreach ($matches as $matchgroup) {

        $author = $matchgroup[$authorCounter];

        $pattern1 = '/\[quote=".+?"\]/'; // captures [quote="..."]
        $replacement1 = '<div class="quote"><strong class="quote-author">' . $author . ' wrote:</strong><br>';
        $p_text = preg_replace($pattern1, $replacement1, $p_text);

        $authorCounter++;
      }

      $pattern2 = '/\[\/quote\]/'; // captures [/quote]
      $replacement2 = '</div>';
      $p_text = preg_replace($pattern2, $replacement2, $p_text);

      return $p_text;

}

这会将两个引用的作者替换为“person2”,因为第二个foreach迭代会再次替换文本(?)。我怎样才能确保每个报价都有正确的人名?

1 个答案:

答案 0 :(得分:0)

只需一个正则表达式即可完成。诀窍是将搜索模式的某些部分放在括号中,并使用$1$2等引用替换模式中的那些部分。

$string = '[quote="person1"]Hello![/quote][quote="person2"]Hi![/quote]';
$output = preg_replace('/\[quote="([^"]+)"\]([^[]+)\[\/quote\]/', '<div class="quote"><strong class="quote-author">$1 wrote:</strong><br>$2</div>', $string);

echo $output;

输出:

<div class="quote"><strong class="quote-author">person1 wrote:</strong><br>Hello!</div>
<div class="quote"><strong class="quote-author">person2 wrote:</strong><br>Hi!</div>

http://sandbox.onlinephpfunctions.com/code/3e8dd7798b29df5bd161eb01f7c11329fc13283f

的实例