当搜索一个字符串时,如何使用strpos
查找多个不同的子字符串?例如:
$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';
if(strpos($string, $find_letters) !== false)
{
echo 'All the letters are found in the string!';
}
因为使用这个时,它不起作用,如果有类似这样的东西就好了。
$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';
if(strpbrk($string, implode($find_letters)) === false)
{
echo 'None of these letters are found in the string!';
}
使用以下代码:
$flag = true;
foreach($find_letters as $letter)
if(false===strpos($string, $letter)) {
$flag = false;
break;
}
然后检查$flag
的值。如果它是true
,则所有字母都已找到。否则,它是false
。
仅仅是对以上答案的升级
function strsearch($findme, $source){
if(is_array($findme)){
if(str_replace($findme, '', $source) != $source){
return true;
}
}else{
if(strpos($source,$findme)){
return true;
}
}
return false;
}
function strposa($haystack, $needle, $offset=0) {
if(!is_array($needle)) $needle = array($needle);
foreach($needle as $query) {
$res=strpos($haystack, $query, $offset);
if($res !== false) return $res; // stop on first true result
}
return false;
}
我正在撰写一篇新答案,希望能帮助到寻找与我类似问题的任何人。
这适用于“我有多个关键词,想要使用它们来查找一个单独的字符串”的情况。这就是我遇到的问题。
$i = 0;
$found = array();
while ($i < count($needle)) {
$x = 0;
while ($x < count($haystack)) {
if (strpos($haystack[$x], $needle[$i]) !== false) {
array_push($found, $haystack[$x]);
}
$x++;
}
$i++;
}
$found = array_count_values($found);
$found
将包含所有匹配的针的列表,具有最高计数值的数组项将是您要查找的字符串,您可以使用以下方法获取它:print_r(array_search(max($found), $found));
<?php
$Words = array("hello","there","world");
$c = 0;
$message = 'Hi hello';
foreach ($Words as $word):
$trial = stripos($message,$word);
if($trial != true){
$c++;
echo 'Word '.$c.' didnt match <br> <br>';
}else{
$c++;
echo 'Word '.$c.' matched <br> <br>';
}
endforeach;
?>