从字符串数组中搜索关键字 (PHP)
Search keywords from array in string (PHP)
$array_keywords = ('red','blue','green');
$string = "Sometimes I'm happy, Sometimes I'm blue, Sometimes I'm sad";
(PHP) 在字符串中搜索关键字(来自数组)并打印巧合,在这种情况下所需的结果应该是 return "blue"。
我该怎么做?
使用这个:
$array_keywords = array('red','blue','green');
$string = 'Sometimes I'm happy, Sometimes I'm blue, Sometimes I'm sad';
foreach ($array_keywords as $keys) {
if (strpos($string, $keys)) {
echo "Match found";
return true;
}
}
echo "Not found!";
return false;
您也可以使用stristr() and stripos()来检查case-insensitive。
或者你可以看到Lucanos answer
检查此代码,
<?php
function strpos_array($haystack, $needles, &$str_return) {
if ( is_array($needles) ) {
foreach ($needles as $str) {
if ( is_array($str) ) {
$pos = strpos_array($haystack, $str);
} else {
$pos = strpos($haystack, $str);
}
if ($pos !== FALSE) {
$str_return[] = $str;
}
}
} else {
return strpos($haystack, $needles);
}
}
// Test
$str = [];
$array_keywords = ('red','blue','green');
$string = "Sometimes I'm happy, Sometimes I'm blue, Sometimes I'm sad";
strpos_array($string, $array_keywords,$str_return);
print_r($str_return);
?>
这是高级 strpos 数组代码。
更精确地满足您的要求的方法是,如果匹配多个元素,则获取数组。
$array_keywords = ('red','blue','green');
$string = "Sometimes I'm happy, Sometimes I'm blue, Sometimes I'm sad";
(PHP) 在字符串中搜索关键字(来自数组)并打印巧合,在这种情况下所需的结果应该是 return "blue"。
我该怎么做?
使用这个:
$array_keywords = array('red','blue','green');
$string = 'Sometimes I'm happy, Sometimes I'm blue, Sometimes I'm sad';
foreach ($array_keywords as $keys) {
if (strpos($string, $keys)) {
echo "Match found";
return true;
}
}
echo "Not found!";
return false;
您也可以使用stristr() and stripos()来检查case-insensitive。
或者你可以看到Lucanos answer
检查此代码,
<?php
function strpos_array($haystack, $needles, &$str_return) {
if ( is_array($needles) ) {
foreach ($needles as $str) {
if ( is_array($str) ) {
$pos = strpos_array($haystack, $str);
} else {
$pos = strpos($haystack, $str);
}
if ($pos !== FALSE) {
$str_return[] = $str;
}
}
} else {
return strpos($haystack, $needles);
}
}
// Test
$str = [];
$array_keywords = ('red','blue','green');
$string = "Sometimes I'm happy, Sometimes I'm blue, Sometimes I'm sad";
strpos_array($string, $array_keywords,$str_return);
print_r($str_return);
?>
这是高级 strpos 数组代码。
更精确地满足您的要求的方法是,如果匹配多个元素,则获取数组。