Php 检查字符串中是否存在数组元素
我原以为用原生php函数实现这一点很简单,但我发现了一些不同的、都相当复杂的方法,人们试图实现它。检查字符串是否包含数组中的一个或多个元素的最有效方法是什么?i、 e,下面-其中$data['description']是一个字符串。Obv下面的in_数组检查中断,因为它希望param 2是一个数组Php 检查字符串中是否存在数组元素,php,arrays,Php,Arrays,我原以为用原生php函数实现这一点很简单,但我发现了一些不同的、都相当复杂的方法,人们试图实现它。检查字符串是否包含数组中的一个或多个元素的最有效方法是什么?i、 e,下面-其中$data['description']是一个字符串。Obv下面的in_数组检查中断,因为它希望param 2是一个数组 $keywords = array( 'bus', 'buses', 'train', ); if (!in_
$keywords = array(
'bus',
'buses',
'train',
);
if (!in_array($keywords, $data['description']))
continue;
您可以使用正则表达式来实现这一点-
if( !preg_match( '/(\b' . implode( '\b|\b', $keywords ) . '\b)/i', $data['description'] )) continue;
结果regexp将是/(\bbus\b |\bbuses\b |\b train\b)/
,假设字符串是折叠/分隔的值列表
例1:
arrayInString( array( 'red' , 'blue' ) , 'red,white,orange' , ',' );
// Would return true
// When 'red,white,orange' are split by ',',
// the 'red' element matched the array
arrayInString( array( 'apple' , 'banana' ) , 'I ate an apple' );
// Would return true
// As 'I ate an apple' contains 'apple'
例2:
arrayInString( array( 'mouse' , 'cat' ) , 'mouse' );
// Would return true
// When 'mouse' is split by ',' (the default deliminator),
// the 'mouse' element matches the array which contains only 'mouse'
arrayInString( array( 'car' , 'bus' ) , 'I was busy' );
// Would return true
// As 'bus' is present in the string, even though it is part of 'busy'
假设字符串是纯文本,您只需在其中查找指定单词的实例
例1:
arrayInString( array( 'red' , 'blue' ) , 'red,white,orange' , ',' );
// Would return true
// When 'red,white,orange' are split by ',',
// the 'red' element matched the array
arrayInString( array( 'apple' , 'banana' ) , 'I ate an apple' );
// Would return true
// As 'I ate an apple' contains 'apple'
例2:
arrayInString( array( 'mouse' , 'cat' ) , 'mouse' );
// Would return true
// When 'mouse' is split by ',' (the default deliminator),
// the 'mouse' element matches the array which contains only 'mouse'
arrayInString( array( 'car' , 'bus' ) , 'I was busy' );
// Would return true
// As 'bus' is present in the string, even though it is part of 'busy'
假设正在搜索整个单词和短语
此函数将从字符串中的短语数组中查找(不区分大小写)短语。如果找到,将重新组合短语,$position返回字符串中的索引。如果未找到,则返回FALSE
function findStringFromArray($phrases, $string, &$position) {
// Reverse sort phrases according to length.
// This ensures that 'taxi' isn't found when 'taxi cab' exists in the string.
usort($phrases, create_function('$a,$b',
'$diff=strlen($b)-strlen($a);
return $diff<0?-1:($diff>0?1:0);'));
// Pad-out the string and convert it to lower-case
$string = ' '.strtolower($string).' ';
// Find the phrase
foreach ($phrases as $key => $value) {
if (($position = strpos($string, ' '.strtolower($value).' ')) !== FALSE) {
return $phrases[$key];
}
}
// Not found
return FALSE;
}
有趣的是,该函数演示了一种查找整个单词和短语的技术,这样就可以找到“bus”而不是“滥用”。只需在干草堆和针周围留出空间:
$pos = strpos(" $haystack ", " $needle ")
我无法让strpos($inString,$inArray)工作。第二个参数不能是strpos中的数组。你真的测试过这个吗?嗨,奥拉夫,谢谢你的评论。我不记得我做了什么测试,因为这个答案是两年前提交的。但是,我已经对代码进行了调整,以便它现在应该遍历数组并执行预期的检查。干净且简单。正是我需要的。