PHP无用的doen';我什么都不匹配


PHP ungreedy doen't match anything

得到的站点有这样的东西:

<html ... data-props="{some_json_data_with_html_entities}" ...>

我正试图用preg_match()获得JSON,但是。。。

使用时:

'~data-props="(.*)"~'

在那之后我得到了所有的东西。。。我的意思是,这一行中有更多包含""的内容,所以它捕获了所有内容…

但使用时:

'~data-props="(.*)"~U'

我什么都没得到。。。结果中为空数组。

发生了什么事?如何正确匹配?

您可能应该使用JSON解析器,但如果您想知道它为什么不起作用(特别是示例2(,那就是个谜。您可能希望匹配lazy,当不使用?量词时,U修饰符会使其匹配。目前还不清楚实际的PHP代码是什么样子的;您的第二个模式应该已经根据输入字符串进行了匹配。

data-props="(.+?)"

+?[lazy]在1和∞次之间匹配,尽可能少的匹配次数,根据需要进行扩展。

https://www.regex101.com/r/cL9xU9/1

这里有一个preg_match使用第二种模式的快速示例,看起来很好:

$str = '<html ... data-props="{some_json_data_with_html_entities}" ... 
       "{some__moar_json_data_with_html_entities}">';
preg_match( '~data-props="(.*)"~U', $str, $res) ;
print_r($res[1]);

结果:

{some_json_data_with_html_entities}

如果它不匹配,那么很明显,我们得到的字符串中有更多。