strpos 存储所有结果而不是第一个阳性
strpos store all results not first positive
我有这个代码。
$needles = explode(" ", $textContentArray);
$haystack = $textContent;
$match_found = strposa($haystack,$needles);
if($match_found) {
echo $match_found ;
}
else {
echo "No match found.";
}
function strposa($haystack, $needles) {
$chr = array();
foreach($needles as $needle) {
$res = stripos($haystack, $needle);
if ($res !== false)
{
$chr[$needle] = $res;
$string_exist = $needle; break;
}
}
if(empty($chr)) return false;
return $string_exist;
}
目前这会输出它找到的第一个匹配项,但是,我希望它输出每个匹配项而不仅仅是第一个。这是因为我在一个网站上使用它,该网站将显示 2 url 之间的任何字符串匹配。
谢谢。
$textContentArray = preg_replace('/(\{|\}|\[|\]|\(|\)|\||\^|$)/', '\$1', $textContentArray);
$needles = array_map('trim',array_filter(explode(' ',$textContentArray)));
preg_match_all('#('.implode('|',$needles).')#is', $haystack, $result);
if(isset($result[1])){
echo '<pre>';
print_r($result);
echo '</pre>';
}else{
echo 'not found';
};
只有 return 匹配您的函数
if(empty($chr)) return false;
return $chr;
}
并删除 break
所以 $match_found
将是数组,例如 ["foo" => 1, "bar" => 4, ...]
我有这个代码。
$needles = explode(" ", $textContentArray);
$haystack = $textContent;
$match_found = strposa($haystack,$needles);
if($match_found) {
echo $match_found ;
}
else {
echo "No match found.";
}
function strposa($haystack, $needles) {
$chr = array();
foreach($needles as $needle) {
$res = stripos($haystack, $needle);
if ($res !== false)
{
$chr[$needle] = $res;
$string_exist = $needle; break;
}
}
if(empty($chr)) return false;
return $string_exist;
}
目前这会输出它找到的第一个匹配项,但是,我希望它输出每个匹配项而不仅仅是第一个。这是因为我在一个网站上使用它,该网站将显示 2 url 之间的任何字符串匹配。
谢谢。
$textContentArray = preg_replace('/(\{|\}|\[|\]|\(|\)|\||\^|$)/', '\$1', $textContentArray);
$needles = array_map('trim',array_filter(explode(' ',$textContentArray)));
preg_match_all('#('.implode('|',$needles).')#is', $haystack, $result);
if(isset($result[1])){
echo '<pre>';
print_r($result);
echo '</pre>';
}else{
echo 'not found';
};
只有 return 匹配您的函数
if(empty($chr)) return false;
return $chr;
}
并删除 break
所以 $match_found
将是数组,例如 ["foo" => 1, "bar" => 4, ...]