简体   繁体   English

preg_match_all和preg_replace foreach循环

[英]preg_match_all and preg_replace foreach loop

I'm trying to convert [quote="author"]text[/quote] to a formatted div block. 我正在尝试将[quote =“ author”] text [/ quote]转换为格式化的div块。

$p_text : $p_text

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

Function: 功能:

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;

}

This is replacing both quote's authors with "person2" because the second foreach iteration replaces the text again(?). 这将两个引用的作者都替换为“ person2”,因为第二次foreach迭代再次替换了文本(?)。 How could I make sure each quote has the correct person's name? 我怎样才能确保每个引号都有正确的人名?

You can do it with just one regex. 您只需要一个正则表达式即可。 The trick is to put certain parts of the search pattern in parenthesis and refer to those parts in the replace pattern using $1 , $2 and so on. 诀窍是将搜索模式的某些部分放在括号中,并使用$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;

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>

Live example at http://sandbox.onlinephpfunctions.com/code/3e8dd7798b29df5bd161eb01f7c11329fc13283f http://sandbox.onlinephpfunctions.com/code/3e8dd7798b29df5bd161eb01f7c11329fc13283f的实时示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM