在字符串中查找特定单词

Finding particular words in string

我想搜索包含Rathi 25mm的字符串,但我不想使用完整的词来搜索。我如何使用特定的词进行搜索?

Rathi Stelmax 500 25 mm in stripos

   <?php
    $title='Rathi Stelmax 500 25 mm';

    if (stripos(strtolower($title), 'Rathi  25 mm') !== false)
    { 
      echo 'true';
    }
    ?>

你可以试试这个脚本

 $title="Rathi Stelmax 500 25 mm";
if(preg_match("/(Rathi|25|mm)/i", $title)){
  //one of these string found
}

最好的方法是使用 preg_match_all。

这是一个 REGEX 函数。 这是一个小例子:

$input_lines = 'Hello i am 250 years old from Mars'
preg_match_all("/(\d+)|(Mars)/", $input_lines, $output_array);

$output_array 将包含一个包含以下数据的数组:

0   =>  array(2
    0   =>  250
    1   =>  Mars
    )

如果您不愿意使用正则表达式,可以将搜索字符串拆分为单词,并检查每个单词是否都包含在字符串中:

$title = 'Rathi Stelmax 500 25 mm';
$lookFor = 'Rathi 25 mm';

$counter = 0;
$searchElements = explode(' ', $lookFor);
foreach($searchElements as $search){
    if(strpos($title, $search) !== false){
        $counter++;
    }
}

if(count($searchElements) == $counter){
    echo 'found everything';
}
else{
    echo 'found ' . $counter . ' element(s)';
}

它可能不如正则表达式有效,但也可能更容易掌握。

有几种方法可以做到这一点。使用您当前的方法,您可以 运行 在条件中使用多个 stripos 来确认每个单词都存在:

$title='Rathi Stelmax 500 25 mm';
if (stripos(strtolower($title), 'Rathi') !== false && stripos(strtolower($title),  '25 mm'))
    { echo 'true';
    }

演示:https://eval.in/628147

您也可以使用正则表达式,例如:

/Rathi.*25 mm/

PHP 演示:https://eval.in/628148
正则表达式演示:https://regex101.com/r/cZ6bL1/1

PHP 用法:

$title='Rathi Stelmax 500 25 mm';
if (preg_match('/Rathi.*25 mm/', $title)) { 
     echo 'true';
}