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

时间:2012-04-13 08:36:43

标签: php arrays

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

$keywords = array(
            'bus',
            'buses',
            'train',
    );

    if (!in_array($keywords, $data['description']))
            continue;

3 个答案:

答案 0 :(得分:8)

假设String是折叠/分隔的值列表

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'

答案 1 :(得分:3)

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

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

结果正则表达式为/(\bbus\b|\bbuses\b|\btrain\b)/

答案 2 :(得分:0)

正在搜索整个单词和短语

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

有趣的是,该功能演示了一种查找整个单词和短语的技术,以便找到“总线”而不是“滥用”。用空间围住干草堆和针头:

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