本文介绍了检查字符串中存在数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想这将是一件简单的事情做一个本地的PHP函数,但我发现人们试图去实现它的几个不同的,所有相当复杂,方法。什么是检查是否一个字符串包含在一个数组中的一个或多个元素的最有效方法是什么?即,下面 - 在$数据['说明']是一个字符串。 OBV低于断in_array检查,因为它预计参数2是一个数组
$关键字=阵列(
'总线',
公交车,
'培养',
); 如果(!in_array($关键字,$数据['说明']))
继续;
解决方案
假定该字符串值的折叠/分隔列表
函数arrayInString($ inArray,$ inString,$ inDelim =''){
$ inStringAsArray =爆炸($ inDelim,$ inString);
返回(计数(array_intersect($ inArray,$ inStringAsArray))大于0);
}
实施例1:
arrayInString(阵列('红','蓝'),红,白,橙','');
//将返回true。
//当红,白,橙'是由分裂',',
//红元素相匹配的数组
例2:
arrayInString(阵列('老鼠','猫'),'鼠');
//将返回true。
//当老鼠是由分裂,(默认deliminator)
//将'鼠标'元素只包含'老鼠'的阵列相匹配
假设字符串是纯文本,而你只是寻找
里面的指定单词的实例 函数arrayInString($ inArray,$ inString){
如果(is_array($ inArray)){
的foreach($ inArray为$ E){
如果(strpos($ inString,$ E)!== FALSE)
返回true;
}
返回false;
}其他{
回报(strpos($ inString,$ inArray)==假的!);
}
}
实施例1:
arrayInString(阵列('苹果','香蕉'),'我吃了一个苹果');
//将返回true。
//为'我吃了一个苹果包含苹果
例2:
arrayInString(阵列('车','公交车'),'我很忙');
//将返回true。
//为总线是present字符串中,即使它的一部分,忙
I thought this would be a simple thing to do with a native php function but i've found a few different, all quite complicated, ways that people have tried to achieve it. What's the most efficient way of checking if a string contains one or more elements in an array? i.e, below - where $data['description'] is a string. Obv the in_array check below breaks because it expects param 2 to be an array
$keywords = array(
'bus',
'buses',
'train',
);
if (!in_array($keywords, $data['description']))
continue;
解决方案
Assuming that the String is a collapsed/delimited list of values
function arrayInString( $inArray , $inString , $inDelim=',' ){
$inStringAsArray = explode( $inDelim , $inString );
return ( count( array_intersect( $inArray , $inStringAsArray ) )>0 );
}
Example 1:
arrayInString( array( 'red' , 'blue' ) , 'red,white,orange' , ',' );
// Would return true
// When 'red,white,orange' are split by ',',
// the 'red' element matched the array
Example 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'
Assuming that the String is plain text, and you are simply looking for instances of the specified words inside it
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 );
}
}
Example 1:
arrayInString( array( 'apple' , 'banana' ) , 'I ate an apple' );
// Would return true
// As 'I ate an apple' contains 'apple'
Example 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'
这篇关于检查字符串中存在数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!