【发布时间】:2019-05-12 23:12:41
【问题描述】:
我想将字符串转换为带有模式的数组。但是我的正则表达式给了我警告。
这是一个字符串:
$string = typ="bar" title="Example" enabled=true count=true style="float: left; width: 30%;"
我的正则表达式:
$regex='/(.*?)[=\"|=](.*?)\"*\s*/';
preg_match_all($regex, $string1, $matchesreg, PREG_SET_ORDER);
正则表达式的输出不正确。最后一个数组必须进一步拆分 $regex='/(.?)="(.?)"\s*/'; preg_match_all($regex, $string1, $matchesreg, PREG_SET_ORDER); 输出
Array
(
[0] => Array
(
[0] => typ="bar"
[1] => typ
[2] => bar
) ...
[2] => Array
(
[0] => enabled=true count=true style="float: left; width: 30%;"
[1] => enabled=true count=true style
[2] => float: left; width: 30%;
)
)
我想要的输出如:
php
Array
(
[0] => Array
(
[0] => typ="bar"
[1] => typ
[2] => bar
)
[1] => Array
(
[0] => title="Example"
[1] => title
[2] => Example
)
[2] => Array
(
[0] => enabled=true
[1] => enabled
[2] => true
)
[3] => Array
(
[0] => count=true
[1] => count
[2] => true
)
[4] => Array
(
[0] => style="float: left; width: 30%;"
[1] => style
[2] => float: left; width: 30%;
)
)
【问题讨论】:
-
试试
preg_match_all('~([^\s=]+)=(?|"([^"]*)"|(\S+))~', $s, $m, PREG_SET_ORDER, 0),见3v4l.org/hJcmW -
谢谢。这可能是正确的正则表达式。今晚我将在我的函数中进一步测试它。
-
很高兴我的回答对你有用。如果我的回答对我有帮助,也请考虑点赞(见How to upvote on Stack Overflow?)。
-
今天中午,投票不想要。只是在另一台计算机上它工作。 ;)
标签: php regex pattern-matching preg-match-all regex-group