简体   繁体   English

php regex-仅匹配1次匹配不匹配一次

[英]php regex - match only for 1 occurrence don't match for more than one

I am trying to write regex that will catch this phrase: 我正在尝试编写正则表达式,以捕获此短语:
background: url("../images/btn-send.png") no-repeat scroll -70px center rgba(0, 0, 0, 0);
but not this: 但不是这个:
background: url("../images/btn-send.png") no-repeat scroll -70px 10px rgba(0, 0, 0, 0);

so I should get match only on ...<number>px ... and not 所以我应该只在...<number>px ...而不是
...<number>px <number>px ....

I have tried to use the next regex: 我试图使用下一个正则表达式:
background\\s*:[^;]*?((-*\\d+px|0)\\s+){1}[az]
I am using it in PHP preg_match 我在PHP preg_match使用它

I had tried to find only one occurrence of px, but it's not working and it's matching both of the strings, can you please help me with that? 我试图仅发现一次px,但它不起作用并且与两个字符串都匹配,您能帮我吗? Thank! 谢谢!

Pending a more elegant answer (I'm not entirely convinced by this one), this would work: 等待一个更优雅的答案(我对此并不完全相信),这将起作用:

<?php
$str1 = 'background: url("../images/btn-send.png") no-repeat scroll -70px  center rgba(0, 0, 0, 0);';
$str2 = 'background: url("../images/btn-send.png") no-repeat scroll -70px   10px   rgba(0, 0, 0, 0);';

var_dump(preg_match('/background\s*:[^;]*?((?<!\dpx|0|\s)\s+(-*\d+px|0)\s+)[a-z]/i',$str1));
var_dump(preg_match('/background\s*:[^;]*?((?<!\dpx|0|\s)\s+(-*\d+px|0)\s+)[a-z]/i',$str2));

So, what does (?<!\\dpx|0|\\s)\\s+ do? 那么, (?<!\\dpx|0|\\s)\\s+什么作用? Is says your Npx/0 should be proceded by at least one whitespace character, but maybe more, not preceded by ( (?<!...) ) either whitespace (ensuring it matches from the first whitespace character when there are several), another Npx , or 0 . 是说您的Npx / 0应该至少包含一个空白字符,但可能要更多,而不要以( (?<!...) )两个空白开头(确保在有多个空白时与第一个空白字符匹配),另外Npx0

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

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