PHP正则表达式匹配句子[重复]



此问题已经存在 这里有一个答案:</ p>





  • PHP字符串替换匹配整个单词



    4 answers

    </ span> \ n </ li>

    </ ul>

    </ div>

    我正在尝试使用PHP和正则表达式比较两个句子,如下所示:</ p>

      $ data =“我是一个有两个孩子的快乐男人”; 
    if(preg_match('/^(?=。* I)(?=。* am)(?=。* happy)( ?=。* with)(?=。* 2)(?=。* kids)/ i',$ data)){echo'matc';} else {echo'not match';}
    </ code> </ pre>

    这似乎工作正常,但如果我将句子更改为:</ p>

      $ data =“我是一个快乐的人 20个孩子“; 
    if(preg_match('/ ^(?=。* I)(?=。* am)(?=。* happy)(?=。* with)(?=。* 2)(?= 。* kids)/ i',$ data)){echo'matc';} else { echo'not match';}
    </ code> </ pre>

    它仍在说匹配。 问题是,不匹配确切的数字,只检查另一个句子上是否有数字2。</ p>
    </ div>

展开原文

原文

This question already has an answer here:

I am trying to compare two sentences using PHP and regex like this:

$data = "I am a happy man with 2 kids";
if (preg_match('/^(?=.*I)(?=.*am)(?=.*happy)(?=.*with)(?=.*2)(?=.*kids)/i', $data)) {echo 'match';} else {echo 'not match';}

and that seems to work fine, but if I change the sentence to:

$data = "I am a happy man with 20 kids";
if (preg_match('/^(?=.*I)(?=.*am)(?=.*happy)(?=.*with)(?=.*2)(?=.*kids)/i', $data)) {echo 'match';} else {echo 'not match';}

It's still saying that matches. The problem is that is not matching the exact number and just checking if theres a number 2 on the other sentence.

</div>

1个回答



添加单词边界:</ p>

  $ data =“我是一个快乐的人 20个孩子“; 
if(preg_match('/^(?=。* I)(?=。* am)(?=。* happy)(?=。* with)(?=。* \ b2 \ b) (?=。* kids)/ i',$ data)){
//这里___ ^^ ^^
echo'matc';
} else {
echo'not match';
} \ n </ code> </ pre>

您可能还想在每个前瞻中添加,但正则表达式将变得不可用</ p>

  $ data =“ 我是一个有20个孩子的快乐男人“; 
if(preg_match('/ ^(?=。* \ bI \ b)(?=。* \ bam \ b)(?=。* \ bhappy \ b)(? =。* \ bwith \ b)(?=。* \ b2 \ b)(?=。* \ bkids \ b)/ i',$ data)){
echo'match';
}其他{\ n echo'not match';
}
</ code> </ pre>
</ div>

展开原文

原文

Add word boundaries:

$data = "I am a happy man with 20 kids";
if (preg_match('/^(?=.*I)(?=.*am)(?=.*happy)(?=.*with)(?=.*\b2\b)(?=.*kids)/i', $data)) {
//                                                 here ___^^ ^^
    echo 'match';
} else {
    echo 'not match';
}

You may want to add also in each lookahead, but the regex will become unredable

$data = "I am a happy man with 20 kids";
if (preg_match('/^(?=.*\bI\b)(?=.*\bam\b)(?=.*\bhappy\b)(?=.*\bwith\b)(?=.*\b2\b)(?=.*\bkids\b)/i', $data)) {
    echo 'match';
} else {
    echo 'not match';
}

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐