检查句子中是否存在多个单词

时间:2015-12-02 06:46:10

标签: php regex

我有以下内容:

句子:

"This is a red apple"

要检查的模式:

red & apple.

要检查的句子和模式都是用户生成的。

$sentence = "This is a red apple";
$words = array('red','apple');
$ch = implode("|",$words);
$pattern = '/[$ch]/';

if(preg_match($pattern, $sentence))
{
  // Do something if the sentence contains red & apple
}

当我执行该代码时,我什么也得不到(没有显示任何内容)。当我对$ pattern进行回显时,它会将其作为整个字符串返回。

我该如何解决这个问题?我错过了什么?

2 个答案:

答案 0 :(得分:2)

更改$pattern = '/[$ch]/';

$pattern = '/('.$ch.')/';$pattern = '/['.$ch.']';

<?php 
$sentence = "This is a red apple";
$words = array('apple','red');
$ch = implode("|",$words);
echo $pattern = '/('.$ch.')/';

if(preg_match($pattern, $sentence))
{
  echo ' Do something if the sentence contains red & apple';
}else
{
  echo 'nothing happpen';
}
?>

检查两个字词是否匹配

<?php 
$sentence = "This is a red apple";
$words = array('red','apple');
$ch = implode("|",$words);
echo $pattern = '['.$ch.']';

if(preg_match_all($pattern, $sentence,$matches) == 2)
{
  echo ' Do something if the sentence contains red & apple';
}else
{
  echo 'nothing happpen';
}

&GT;

您还可以检查使用

匹配的单词数量
echo count($matches[0]);

$matches数组包含匹配的字

答案 1 :(得分:1)

在使用需要更新的引号内的变量时,您需要注意quotes

$pattern = "/($ch)/";
          ^^ ^^ ^^ ^^

$sentence = "This is a red apple";
$words = array('red','apple');
$ch = implode("|",$words);
$pattern = "/($ch)/";
if(preg_match_all($pattern, $sentence,$m))
{
  echo "yes \n";
  print_r($m);
}

您还需要更新正则表达式模式,因此您的代码看起来像

regex

而不是array_intersect我将str_word_count$sentence = "This is a red apple"; $words = array('red','apple','blue'); $var = count(array_intersect(str_word_count($sentence,1),$words)); if(count($words == $var)){ echo "Yes got it"; } 一起使用,如

<?php 
    // start first row
    echo "<hr class='margin-bottom-40'>";
    echo "<div class='row blog blog-medium margin-bottom-40'>";
    foreach ($m->result() as $row)  {
        $Player=$row->image;
        echo "<div class='col-sm-4'>";
        echo "<div class='news-v2-badge'><img class='img-responsive' style='' src='http://opunletter.com/" .  $Player . "'";
        echo "</div>";
        echo "<p><span>23</span><small>Jan</small></p>";
        echo "<div class='post-caption'>";
        echo "<ul class='post-inline block-grid-v1-add-info'>";
        echo "<li><a href='#'><i class='fa fa-eye'></i> 34039</a></li>";
        echo "<li><a href='#'><i class='fa fa-thumbs-o-up'></i> 451</a></li>";
        echo "<li><a href='#'><i class='fa fa-thumbs-o-down'></i> 863</a></li>";
        echo "</ul>"; 
        echo "</div>";
        echo "</div>";
        echo "<div class='news-v2-desc'>";
        echo "<h3><a href='#'>Reading Some Books</a></h3>";
        echo "<small>By Admin | California, US | In <a href='#'>Art</a></small>";
        echo "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio.</p>";
        echo "</div>";
        echo "</div>";
    }
?>

Demo

Demo2