开发者

How to detect second occurrence using regex? (php)

开发者 https://www.devze.com 2023-04-04 12:46 出处:网络
From this question How to match this using regex开发者_运维问答 Right now i want to search for 3D D keyword from user submitted data. The rule is as long as 3D and D is present in the sentence, it is

From this question How to match this using regex开发者_运维问答

Right now i want to search for 3D D keyword from user submitted data. The rule is as long as 3D and D is present in the sentence, it is valid (case insensitive).

For example:

3Dzzzzzzzzzzzzzzzzzzz (invalid because no second occurence of D)

zzzzzD (invalid because no 3D)

xxx3DzzzzzD (valid because got 3D and D in string)

I am using this regex now but somehow it has one problem.

$subject = 'BLASHSH*3D*8qw9e08e2323*D*';

if(preg_match('/(?=.*3D)(?=.*D).*/i', $subject))
{
    echo 'pattern match';
}
else
{
    echo 'fail';
}

The problem is this string also will return true

3D (it should be invalid because no second occurrence of D)

3D ABC (it should be invalid because no second occurrence of D)

How to solve this?


Assuming 3DD, D3D, and cccDzzz3D are all valid:

/(3D.*D)|(D.*3D)/i

And since you used the i modifier before I assume you want to accept 3d and d? If not just remove the i from the end of the regex.


If the rule is that 3D must appear before D and can have any number of characters before, after, or in between (including zero characters), this should be sufficient:

/3D.*D/i
0

精彩评论

暂无评论...
验证码 换一张
取 消