5

I am using preg_match() to extract pieces of text from a variable, and let's say the variable looks like this:

[htmlcode]This is supposed to be displayed[/htmlcode]

middle text

[htmlcode]This is also supposed to be displayed[/htmlcode]

i want to extract the contents of the [htmlcode]'s and input them into an array. i am doing this by using preg_match().

preg_match('/\[htmlcode\]([^\"]*)\[\/htmlcode\]/ms', $text, $matches);
foreach($matches as $value){
return $value . "<br />";
}

The above code outputs

[htmlcode]This is supposed to be displayed[/htmlcode]middle text[htmlcode]This is also supposed to be displayed[/htmlcode]

instead of

  1. [htmlcode]This is supposed to be displayed[/htmlcode]
  2. [htmlcode]This is also supposed to be displayed[/htmlcode]

and if have offically run out of ideas

4

4 回答 4

4

如前所述;*模式是贪婪的。另一件事是使用preg_match_all()函数。它会返回一个匹配内容的多维数组。

preg_match_all('#\[htmlcode\]([^\"]*?)\[/htmlcode\]#ms', $text, $matches);
foreach( $matches[1] as $value ) {

你会得到这个:http ://codepad.viper-7.com/z2GuSd

于 2013-05-09T23:27:40.137 回答
3

石斑鱼是贪婪的*,即它会吃掉所有东西直到最后 [/htmlcode]。尝试用*non-greedy替换*?

于 2013-05-09T23:22:03.907 回答
2

*默认情况下是贪婪的,([^\"]*?)(注意添加的?)应该使它变得懒惰。

于 2013-05-09T23:22:01.643 回答
2

看这段代码:

preg_match('/\[htmlcode\]([^\"]*)\[\/htmlcode\]/ms', $text, $matches);
foreach($matches as $value){
return $value . "<br />";
}

现在,如果您的模式工作正常并且一切正常,您应该知道:

  • return语句将中断所有循环并退出函数。
  • 匹配中的第一个元素是整个匹配,整个字符串。在你的情况下$text

所以,你所做的是返回第一个大字符串并退出函数。

我建议您可以检查所需的结果:

$matches[1]$matches[2]

于 2013-05-09T23:22:23.067 回答