简体   繁体   中英

How to detect second occurrence using regex? (php)

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.

如果规则是3D必须出现在D之前,并且可以在D之前,之后或之间包含任意数量的字符(包括零个字符),则这足够了:

/3D.*D/i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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