2013-05-02 43 views
0

我有一个字符串:的preg_match与UTF8

$string = 'This is Test'; 

而且也字数组:

$array = array('test','example','blahblah'); 

我想看看到$字符串,看看是否有任何的话$数组与否的:

$string_arr = explode(' ', $string); 
foreach($string_arr as $value){ 
    if (preg_match("/\b$value\b/iu", $array)) 
     return true; 
} 

正如你看到的,我用了“u”标志为UTF-8支持,但有线的是,这个工作对我的WAMP(localh OST),但我在它不工作的CentOS真正的服务器上,我用Google搜索,我发现这一点: http://chrisjean.com/2009/01/31/unicode-support-on-centos-52-with-php-and-pcre/

但是,我没有访问服务器升级RPM,所以,我应该怎么办呢?

在此先感谢


任何人都可以想出另一种解决办法?我感谢任何帮助。

+0

您不必在的话你'$ array' Unicode字符。另外,你可以用一个正则表达式来完成这种匹配。另外,当需要一个字符串时,你将一个数组传递给'preg_match()'的第二个参数。 – nickb 2013-05-02 13:27:54

回答

1

我不知道你是否能得到比这更简单:array_intersect($array,explode(' ',$string));你会基本上只是和检查,如果返回的数组的任何值会告诉你$ array中的任何单词是否在$ string中。以下是测试和工作。

if(count(array_intersect($array,explode(' ',$string))) > 0) 
{ 
    echo 'We have a match!'; 
} 

对于有完整的代码块的缘故...

$string = 'This is Test'; 
$array = array('test','example','blahblah'); 
$checked_array = array_intersect($array,explode(' ',$string)); 

if(count($checked_array) > 0) 
{ 
    echo 'The following words matched: '.implode(', ',$checked_array); 
} 
0
$testArray = explode(' ', $string); 
foreach($testArray as $value){ 
    if(array_search($value, $testArray) !== false) return true; 
} 
+0

这种看起来像是矫枉过正,或者至少是效率低下。当您可以直接比较数组时,不需要逐个遍历所有值。我不同意这是被接受的答案。 – Chad 2013-05-02 13:50:02

+0

@cwscribner然后感谢让我知道:-) – behz4d 2013-05-02 13:56:38

+1

@ behz4d没问题。我只是想确保你对你的问题有一个实质性的答案。它可能会不用说,但$ $ checked_array'变量包含所有匹配的单词,无论出于何种原因,您都需要访问这些单词。如果你不这样做,我会建议使用我提供的第一位代码,这样你就不会浪费分配变量的内存。 – Chad 2013-05-02 14:02:01

0

,而不是使用的preg_match使用array_search

$key = array_search($string, $array); 
if(empty($key)) 
return true; 
else 
return false; 
+0

'in_array()'可以[v](http://stackoverflow.com/questions/6093890/php-in-array-horrible-performance-fatest-way-to-search-array-for-value)[er ](http://stackoverflow.com/questions/13483219/what-is-faster-in-array-or-isset)[Y](http://forums.phpfreaks.com/topic/237190-in-array-非常慢的表现/)[sl](http://brian.moonspot.net/2008/06/05/in_array-is-quite-slow/)[ow](http://lucb1e.com/?p =交&ID = 97) – 2014-04-30 07:30:23