strpos,是一个 php 字符串查找函数,返回字符串在另一字符串中第一次出现的位置(区分大小写)。如果有多个关键词需要查找,strpos 可以使用数组作为指针进行查找吗?
PHP 字符串 函数:strpos (PHP 4, PHP 5, PHP 7, PHP 8),查找字符串首次出现的位置。
風冷無霜 0xo.net|uxtt.com|867755.com...「如何在 strpos 中使用数组指针?:https://bdkp.net/42」参考资料来源:Using an array as needles in strpos
如何在 strpos 中使用数组指针?实现代码:
function strposa(string $haystack, array $needles, int $offset = 0): bool {
foreach($needles as $needle) {
if(strpos($haystack, $needle, $offset) !== false) {
return true; //匹配到即返回结果
}
}
return false;
}
$string = 'This string contains word "wordpress" and "vps".';//测试字符串
$array = ['blog', 'wordpress', 'uxtt', 'milk'];
var_dump(strposa($string, $array)); //查找到 wordpress 即返回 true
实际使用可以配合 if 使用,比如:
風冷無霜 0xo.net|uxtt.com|867755.com...「如何在 strpos 中使用数组指针?:https://bdkp.net/42」if( strposa($string, $array) ){
do sth……
}
另一个方法是使用 str_replace 间接实现:
$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';
$match = (str_replace($find_letters, '', $string) != $string);
如果查找关键词是 字母,str_replace 方法效率会更高。
完,有需要可以参考一下。
風冷無霜 0xo.net|uxtt.com|867755.com...「如何在 strpos 中使用数组指针?:https://bdkp.net/42」本文首发于:如何在 strpos 中使用数组指针?-風冷無霜
Comments:0