2012-04-10 47 views
1

不幸的是,由于一些奇怪的原因,正则表达式方法不适合UTF-8(preg_replace + UTF-8 doesn't work on one server but works on another)。最有效的方法来检测文本中的一组单词没有正则表达式

什么是最有效的方式来实现我的目标,而不使用正则表达式?

只是为了使其尽可能明确,下列词语集:
猫,狗,天空

猫将返回false
天空是蓝色的将返回true
天际将返回false

+0

您使用的是哪个版本的PHP? – 2012-04-10 02:16:18

回答

1

超级简单的例子,但这是我没有正则表达式的方式。

$haystack = "cats"; //"the sky is blue"; // "skyrim"; 
$needles = array("cat", "dog", "sky"); 

$found = false; 
foreach($needles as $needle) 
    if(strpos(" $haystack ", " $needle ") !== false) { 
     $found = true; 
     break; 
    } 


echo $found ? "A needle was found." : "A needle was not found."; 
+1

你有没有机会打电话给['substr_count'](http://php.net/manual/en/function.substr-count.php)? ;-) – Basti 2012-04-10 01:54:03

+1

我也认为'strpos'将在这个解决方案中表现更好,因为只有'$ heystack'包含'$ needle'而不是发生的数量时才会使用Lior。请参阅http://stackoverflow.com/a/3875258/1220835 – Basti 2012-04-10 01:56:13

+0

@Basti'strpos!== false',好吗? – iambriansreed 2012-04-10 02:00:16

1

我最初的想法是分解空间上的文本,然后检查是否存在于结果数组中。当然,你也可能会有一些标点符号泄露到你的数组中,你必须考虑。

另一个想法是检查这个词的strpos。如果找到了,请检查下一个字符以查看它是否是字母。如果它是一封信,你知道你已经找到了一个单词的潜台词,并且放弃了这个发现。

// Test online at http://writecodeonline.com/php/ 

$aWords = array("I", "cat", "sky", "dog"); 
$aFound = array(); 
$sSentence = "I have a cat. I don't have cats. I like the sky, but not skyrim."; 

foreach ($aWords as $word) { 
    $pos = strpos($sSentence, $word); 
    // If found, the position will be greater than or equal to 0 
    if (!($pos >= 0)) continue; 
    $nextChar = substr($sSentence , ($pos + strlen($word)), 1); 
    // If found, ensure it is not a substring 
    if (ctype_alpha($nextChar)) continue; 
     $aFound[] = $word; 
} 

print_r($aFound); // Array ([0] => I [1] => cat [2] => sky) 

当然更好的解决方案是,以确定为什么您不能使用正则表达式,因为这些解决方案将远不及高效的模式寻求将。

+0

事情是 - 处理非常大的文本时真的是最有效的方式吗? – Lior 2012-04-10 01:35:48

+3

@Lior最有效的方法是弄清楚如何获得正则表达式。这远没有那么有效。 – Sampson 2012-04-10 01:37:02

+0

我只是无法弄清楚我的生活...我真的不知道为什么它不工作,不能再等了,不幸的是我必须使用另一种解决方案。 – Lior 2012-04-10 01:40:06

0

如果你只是想找到,如果一个词是在一个字符串,你可以存储在一个变量的字符串(如打印字符串打印变量,里面的字符串代替),并使用“中”。例如:

a = 'The sky is blue' 
The in a 
True 
+0

这看起来不像PHP代码... – user13500 2014-03-04 01:49:38

相关问题