Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/245.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在php中使用正则表达式多次查找字符之间的字符串值_Php_Regex - Fatal编程技术网

在php中使用正则表达式多次查找字符之间的字符串值

在php中使用正则表达式多次查找字符之间的字符串值,php,regex,Php,Regex,这里我有一个字符串,“你好,世界!我正在用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 try

这里我有一个字符串,
“你好,世界!我正在用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\u match\u all()
,但我认为我没有正确使用它,或者在这种情况下它根本不起作用。

您可以使用:

$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!
)

即使您的正则表达式
\*\*(.*)\*\*\\\*\\\\\\\\\\\\\\\\\\\\\\\\\\/code>也应该使用它,但我建议的正则表达式效率稍高一些,因为基于否定的模式
[^*]*

由于使用preg\u match,您得到了1个匹配。您应该使用preg\u match\u这里是另一个模式。它在分隔符之间使用单词-非单词匹配

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

我建议您使用非贪婪形式的正则表达式。因为我认为您还希望匹配单个
*
所在的内容(在**内的文本)

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