admin管理员组文章数量:1125561
I have this string:
1 x red 1 x blue 3 x yellow
and I want to turn it into:
1 x red
1 x blue
3 x yellow
How can I do this please? I have tried using php preg_match but no luck
$description = "1 x red 1 x blue 3 x yellow";
preg_match('/[0-9] x (.*?){[0-9] x /',$description,$matches);
var_dump($matches);
I have this string:
1 x red 1 x blue 3 x yellow
and I want to turn it into:
1 x red
1 x blue
3 x yellow
How can I do this please? I have tried using php preg_match but no luck
$description = "1 x red 1 x blue 3 x yellow";
preg_match('/[0-9] x (.*?){[0-9] x /',$description,$matches);
var_dump($matches);
Share
Improve this question
edited 2 days ago
Youri
asked 2 days ago
YouriYouri
133 bronze badges
2
- What is the difference? Just spaces around? – Markus Zeller Commented 2 days ago
- sorry, they need to be on the next line, I have updated my question – Youri Commented 2 days ago
1 Answer
Reset to default 0I'd use preg_match_all()
and then just provide the pattern for a single entity:
$str = '1 x red 1 x blue 3 x yellow';
preg_match_all('/\d+\s+x\s+\S+/', $str, $matches);
print_r($matches);
Array
(
[0] => Array
(
[0] => 1 x red
[1] => 1 x blue
[2] => 3 x yellow
)
)
You might also use preg_split()
where the split pattern is something like, non-digit before a space then digit after the space -- but I would imagine this is somewhat more fragile:
print_r(preg_split('/(?<=\D) (?=\d)/', $str));
Array
(
[0] => 1 x red
[1] => 1 x blue
[2] => 3 x yellow
)
本文标签: preg matchphp pregmatch finding string between two pattersStack Overflow
版权声明:本文标题:preg match - php preg_match finding string between two patters - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736632865a1945814.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论