在php中使用regex多次查找字符之间的字符串值

时间:2015-03-21 14:26:05

标签: php regex

这里我有一个字符串"Hello World! I am trying out regex in PHP!"。我想要做的是检索一组字符之间的字符串值。在此示例中,字符为** **

$str = "**Hello World!** I am trying out regex in PHP!";
preg_match('#\*\*(.*)\*\*#Us', $str, $match);
echo $match[1];

这将回应“Hello World!”,但我想回应几个匹配:

$str = "**Hello World!** I am trying out **regex in PHP!**";

我怎么能这样做?我尝试使用preg_match_all(),但我认为我没有正确使用它,或者在这种情况下它会起作用。

3 个答案:

答案 0 :(得分:2)

您可以使用:

$str = "**Hello World!** I am trying out **regex in PHP!**";
preg_match_all('/\*{2}([^*]*)\*{2}/', $str, $m);

print_r($m[1]);
Array
(
    [0] => Hello World!
    [1] => regex in PHP!
)

即使您的正则表达式#\*\*(.*)\*\*#Us应该可以使用此功能,但由于基于否定的模式[^*]*

,我建议的正则表达式效率更高一些

答案 1 :(得分:1)

由于使用了preg_match,你得到了1场比赛。你应该使用preg_match_all这是另一种模式。它在分隔符之间使用单词非单词匹配

<?php
    $str = "**Hello World!** I am trying out **regex in PHP!**";
    $regex='/\*\*([\w\W]*)\*\*/iU';
    preg_match_all($regex, $str, $m); 
    print_r($m[1]);

答案 2 :(得分:1)

我建议你使用非贪婪的正则表达式。因为我认为你想要匹配单*所在的内容( ** 中的文本)。

$str = "**Hello World!** I am trying out **regex in PHP!**";
preg_match_all('~\*\*(.*?)\*\*~', $str, $matches);
print_r($matches[1]);

DEMO