繁体   English   中英

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

[英]Check if array element exists in string

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

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

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

假设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'

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

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

结果regexp将是/(\\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'.";
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM