简体   繁体   English

php regex_replace在第一场比赛后停止

[英]php regex_replace stop after first match

I am trying to replace the first occurnce of css size(px|pt|em) with - so this: 我试图用 - 替换css大小的首次出现(px | pt | em) - 所以这个:
64px 64px #123456 will become: 64px 64px #123456将成为:
-64px 64px #123456

I am using the next regex: 我正在使用下一个正则表达式:
preg_replace("/((-*\\d+(?:px|e[mx]|%)?)\\s(-*\\d+(?:px|e[mx]|%)?)){1,1}?/si", "-$1", $input_lines);

it works great when there are only 2 sets of sizes but when there are 4 like: 当只有2套尺寸但是当有4套时,它的效果很好:
64px 64px 12px 12px #123456 in get the next results: 64px 64px 12px 12px #123456获得下一个结果:
-64px 64px -12px 12px #123456 . -64px 64px -12px 12px #123456 what can I do to stop it after the first occurrence? 我可以做些什么来在第一次发生后阻止它? Thanks! 谢谢!

With the 4. argument of preg_replace you can limit how much replace you would like to do: 使用preg_replace的4.参数,您可以限制您想要做多少替换:

http://php.net/preg_replace http://php.net/preg_replace

limit 限制

 The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit). 

So you should use this way: 所以你应该这样使用:

preg_replace("/((-*\d+(?:px|e[mx]|%)?)\s(-*\d+(?:px|e[mx]|%)?)){1,1}?/si",
"-$1", $input_lines, 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM