php搜索字符串查找单词如果找不到,则搜索其他单词
我想在一个字符串中搜索一个单词,如果找不到这个单词,我想让它搜索另一个单词,然后继续搜索,直到找到一个为止。我看到了搜索字符串但不继续搜索的代码 干杯 艾希礼 我需要的是p.s php代码 非常感谢你们的帮助,伙计们php搜索字符串查找单词如果找不到,则搜索其他单词,php,search,loops,Php,Search,Loops,我想在一个字符串中搜索一个单词,如果找不到这个单词,我想让它搜索另一个单词,然后继续搜索,直到找到一个为止。我看到了搜索字符串但不继续搜索的代码 干杯 艾希礼 我需要的是p.s php代码 非常感谢你们的帮助,伙计们 我将在以后发布我的wip代码,感谢您的提示。如果您将所有值放置在要搜索的数组中,您可以在该数组中循环,直到找到字符串中的值为止 $string = "I love to eat tacos."; $searchfor = array("brown", "lazy", "tacos"
我将在以后发布我的wip代码,感谢您的提示。如果您将所有值放置在要搜索的数组中,您可以在该数组中循环,直到找到字符串中的值为止
$string = "I love to eat tacos.";
$searchfor = array("brown", "lazy", "tacos");
foreach($searchfor as $v) {
if(strpos($string, $v)) {
//Found a word
echo 'Found '.$v;
break;
}
}
这将产生:
Found tacos
这是使用区分大小写的strpos。如果您不关心大小写,可以使用stripos
很简单:
$string = "This is the string I want to search in for a third word";
$words = array('first', 'second', 'third');
$found = '';
foreach ($words as $word) {
if (stripos($string, $words) !== false) {
$found = $word;
break;
}
}
echo "This first match found was '$found'";
注意:使用(或用于不区分大小写的搜索),因为它们只返回整数位置。其他的,如返回字符串的一部分,这是不必要的
编辑:
或者,如果没有循环,您可以执行单个正则表达式:
$words = array('first', 'second', 'third');
$regex = '/(' . implode('|', $words) . ')/i';
//$regex becomes '/(first|second|third)/i'
if (preg_match($regex, $string, $match)) {
echo "The first match found was {$match[0]}";
}
比如:
$haystack = 'PHP is popular and powerful';
$needles = array('Java','Perl','PHP');
$found = '';
foreach($needles as $needle) {
if(strpos($haystack,$needle) !== false) {
$found = $needle;
break;
}
}
if($found !== '') {
echo "Needle $found found in $haystack\n";
} else {
echo "No needles found\n";
}
以上代码将考虑子字符串匹配作为有效匹配。例如,如果指针是
'HP'
,它将被发现,因为它是PHP
的子字符串
要进行完整的单词匹配,您可以使用preg\u match
作为:
foreach($needles as &$needle) {
$needle = preg_quote($needle);
}
$pattern = '!\b('.implode('|',$needles).')\b!';
if(preg_match($pattern,$haystack,$m)) {
echo "Needle $m[1] found\n";
} else {
echo "No needles found\n";
}
你是说
<?php
function first_found(array $patterns, $string) {
foreach ($patterns as $pattern) {
if (preg_match($pattern, $string, $matches)) {
return $matches;
}
}
}
$founded = first_found(
array(
'/foo/',
'/bar/',
'/baz/',
'/qux/'
),
' yep, it qux.'
);
很高兴有人为您编写了此代码。通常,最好至少自己编写代码,并向我们提供无法帮助您解决问题的代码。strpos
应在此处使用,而不是strstr
,请参阅您链接到的手册页上的注释:)@mfonda谢谢,我想我真的是指strpos,但我只是匆匆忙忙地做完了。我更新了我的答案以反映正确的想法。