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

Stop regex splitting on whitespace

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

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

我的问题是我的循环和正则表达式正在拆分空格,我不知道如何更改它以使其不拆分。

我试过将 \w 添加到 = 符号的右侧,但没有成功。

结果

{"for":"products","showPagination":"true","paginationPosition":"both","wrapLoop":"true","returnDefaultNoResults":"true","noResultsHeading":"Nothing","noResultsHeadingSize":"2","noResultsParagraph":"We"}

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

我建议您更改 preg_match_all 函数,如下所示。

preg_match_all('/([a-zA-Z]+)=("[^"]*"|\S+)/', str_replace('&quot;', '"', $content), $attr);

它会优先匹配所有双引号的内容。如果没有任何双引号块,那么它将匹配一个或多个非space字符。

输出:

{"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."}