检查字符串中是否存在数组元素


Check if array element exists in string

我认为使用本机php函数是一件简单的事情,但是我发现了一些不同的,都非常复杂的方法,人们试图实现它。检查字符串是否包含数组中的一个或多个元素的最有效方法是什么?即,在下面 - 其中$data['description']是一个字符串。Obv 下面的in_array检查中断,因为它期望参数 2 是一个数组

$keywords = array(
            'bus',
            'buses',
            'train',
    );
    if (!in_array($keywords, $data['description']))
            continue;

假设字符串是折叠/分隔的值列表

function arrayInString( $inArray , $inString , $inDelim=',' ){
  $inStringAsArray = explode( $inDelim , $inString );
  return ( count( array_intersect( $inArray , $inStringAsArray ) )>0 );
}

示例 1:

arrayInString( array( 'red' , 'blue' ) , 'red,white,orange' , ',' );
// Would return true
// When 'red,white,orange' are split by ',',
// the 'red' element matched the array

示例 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'

假设 String 是纯文本,并且您只是在其中查找指定单词的实例

function arrayInString( $inArray , $inString ){
  if( is_array( $inArray ) ){
    foreach( $inArray as $e ){
      if( strpos( $inString , $e )!==false )
        return true;
    }
    return false;
  }else{
    return ( strpos( $inString , $inArray )!==false );
  }
}

示例 1:

arrayInString( array( 'apple' , 'banana' ) , 'I ate an apple' );
// Would return true
// As 'I ate an apple' contains 'apple'

示例 2:

arrayInString( array( 'car' , 'bus' ) , 'I was busy' );
// Would return true
// As 'bus' is present in the string, even though it is part of 'busy'

您可以使用正则表达式执行此操作 -

if( !preg_match( '/('b' . implode( ''b|'b', $keywords ) . ''b)/i', $data['description'] )) continue;

结果正则表达式将/('bbus'b|'bbuses'b|'btrain'b)/

假设正在搜索整个单词和短语

此函数将从字符串中的短语数组中查找(不区分大小写)短语。如果找到,则重新调用该短语,$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;
}

要测试函数,

$wordsAndPhrases = array('taxi', 'bus', 'taxi cab', 'truck', 'coach');
$srch = "The taxi cab was waiting";
if (($found = findStringFromArray($wordsAndPhrases, $srch, $pos)) !== FALSE) {
    echo "'$found' was found in '$srch' at string position $pos.";
}
else {
    echo "None of the search phrases were found in '$srch'.";
}

有趣的是,该函数演示了一种查找整个单词和短语的技术,以便找到"bus"而不是"滥用"。只需用空间包围您的大海捞针和针

$pos = strpos(" $haystack ", " $needle ")