您好我正在尝试检查字符串中是否存在单词列表(或其中任何一个单词)。我尝试了一些我在这里找到的例子,但我还是无法让它正常工作。
任何想法我做错了什么?
$ss3="How to make a book";
$words = array ("book","paper","page","sheet");
if (in_array($ss3, $words) )
{
echo "found it";
}
答案 0 :(得分:2)
循环遍历数组,检查字符串
中是否存在每个元素$ss3="How to make a book";
$words = array ("book","paper","page","sheet");
foreach($words as $w){
if (stristr($ss3,$w)!==false)
echo "found $w \n";
}
<强> Fiddle 强>
答案 1 :(得分:0)
您需要explode()
$ss3
字符串,然后将每个项目与$words
循环进行比较
in_array
- http://php.net/manual/en/function.in-array.php
explode()
- http://php.net/manual/ru/function.explode.php
$matches = array();
$items = explode(" ",$ss3);
foreach($items as $item){
if(in_array($item, $words)){
$matches[] = $item; // Match found, storing in array
}
}
var_dump($matches); // To see all matches
答案 2 :(得分:0)
这是检查字符串中是否存在单词的方法。另请记住,您必须首先将字符串转换为小写,然后将其展开。
$ss3="How to make a book";
$ss3 = strtolower($ss3);
$ss3 = explode(" ", $ss3);
$words = array ("book","paper","page","sheet");
if (in_array($ss3, $words) )
{
echo "found it";
}
干杯!
答案 3 :(得分:0)
您可以将str_word_count
与array_intersect
一起使用,如
$ss3="How to make a book";
$words = array ("book","paper","page","sheet");
$new_str_array = str_word_count($ss3,1);
$founded_words = array_intersect($words,$new_str_array);
if(count($founded_words) > 0){
echo "Founded : ". implode(',',$founded_words);
}else{
echo "Founded Nothing";
}
答案 4 :(得分:0)
您可以使用正则表达式。它看起来像这样:
$ss3 = "How to make a book";
if (preg_match('/book/',$ss3))
echo 'found!!';
答案 5 :(得分:0)
in_array只会检查数组中的完整字符串值。 现在你可以试试这个:
$string = 'How to make a book';
$words = array("book","paper","page","sheet");
foreach ($words as $val) {
if (strpos($string, $val) !== FALSE) {
echo "Match found";
return true;
}
}
echo "Not found!";
答案 6 :(得分:0)
此代码将帮助您更好地回答
<?php
$str="Hello World Good";
$word=array("Hello","Good");
$strArray=explode(" ",$str);
foreach($strArray as $val){
if(in_array($val,$word)){
echo $val."<br>";
}
}
?>