[英]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;
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'
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.