Php 停止在空格上拆分正则表达式

Php 停止在空格上拆分正则表达式,php,regex,parsing,preg-match-all,Php,Regex,Parsing,Preg Match All,我正在编写一个解析器,试图自动化一种方法,可以将任何参数作为参数传递,如下所示: $content = '{loop for=products showPagination="true" paginationPosition="both" wrapLoop="true" returnDefaultNoResults="true" noResultsHeading="Nothing Found" noResultsHeadingSize="2" noResultsParagraph="We hav

我正在编写一个解析器,试图自动化一种方法,可以将任何参数作为参数传递,如下所示:

$content = '{loop for=products showPagination="true" paginationPosition="both" wrapLoop="true" returnDefaultNoResults="true" noResultsHeading="Nothing Found" noResultsHeadingSize="2" noResultsParagraph="We have not found any products in this category, please try another."}{/loop}';
preg_match_all('/([a-zA-Z]+)=([\/\.\"a-zA-Z0-9&;,_-]+)/', str_replace('"', '"', $content), $attr);

if (!is_array($attr)) return array();

for ($z = 0; $z < count($attr[1]); $z++) if (isset($attr['1'][$z])) $attrs[$attr['1'][$z]] = trim($attr['2'][$z], '"');

echo json_encode($attrs);

您会注意到最后两个参数都在第一个单词后停止。

我建议您更改
preg\u match\u all
函数,如下所示

preg_match_all('/([a-zA-Z]+)=("[^"]*"|\S+)/', str_replace('&quot;', '"', $content), $attr);
它将首先贪婪地匹配所有双引号内容。如果没有任何双引号块,则它将匹配一个或多个非空格字符

输出:

{"for":"products","showPagination":"true","paginationPosition":"both","wrapLoop":"true","returnDefaultNoResults":"true","noResultsHeading":"Nothing Found","noResultsHeadingSize":"2","noResultsParagraph":"We have not found any products in this category, please try another."}
{"for":"products","showPagination":"true","paginationPosition":"both","wrapLoop":"true","returnDefaultNoResults":"true","noResultsHeading":"Nothing Found","noResultsHeadingSize":"2","noResultsParagraph":"We have not found any products in this category, please try another."}