php regex_replace在第一场比赛后停止

时间:2013-11-26 13:18:52

标签: php regex preg-replace

我正在尝试用 - 替换css大小的首次出现(px | pt | em) 所以这个:
64px 64px #123456 将成为:
-64px 64px #123456

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

当只有2套尺寸但有4种情况时它很有效:
64px 64px 12px 12px #123456获取下一个结果:
-64px 64px -12px 12px #123456。 我可以做些什么来在第一次发生后阻止它? 谢谢!

1 个答案:

答案 0 :(得分:3)

使用preg_replace的4.参数,您可以限制您想要做多少替换:

http://php.net/preg_replace

  

限制

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

所以你应该这样使用:

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