简体   繁体   English

如何使用正则表达式检测第二次出现? (php)

[英]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. 现在,我想从用户提交的数据中搜索3D D关键字。 The rule is as long as 3D and D is present in the sentence, it is valid (case insensitive). 只要句子中存在3D和D,该规则就有效(不区分大小写)。

For example: 例如:

3Dzzzzzzzzzzzzzzzzzzz (invalid because no second occurence of D) 3Dzzzzzzzzzzzzzzzzzzzzz(无效,因为没有第二次出现D)
zzzzzD (invalid because no 3D) zzzzzD(无效,因为没有3D)
xxx3DzzzzzD (valid because got 3D and D in string) xxx3DzzzzzD(有效,因为在字符串中包含3D和D)

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 问题是此字符串也将返回true

3D (it should be invalid because no second occurrence of D) 3D(应该无效,因为没有第二次出现D)
3D ABC (it should be invalid because no second occurrence of D) 3D ABC(它应该无效,因为没有第二次出现D)

How to solve this? 如何解决呢?

Assuming 3DD , D3D , and cccDzzz3D are all valid: 假设3DDD3DcccDzzz3D均有效:

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

And since you used the i modifier before I assume you want to accept 3d and d ? 并且由于您在我假设要接受3dd之前使用过i修饰符? If not just remove the i from the end of the regex. 如果不是,则从正则表达式的末尾删除i

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

/3D.*D/i

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

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