【问题标题】:Most efficient way to detect a set of words in a text without regex在没有正则表达式的情况下检测文本中一组单词的最有效方法
【发布时间】:2012-04-10 01:28:58
【问题描述】:

不幸的是,由于某种奇怪的原因,正则表达式方法不适用于 UTF-8 (preg_replace + UTF-8 doesn't work on one server but works on another)。

在不使用正则表达式的情况下实现我的目标的最有效方法是什么?

只是为了尽可能清楚,对于以下一组词:
猫,狗,天空

cats 会返回 false
天空是蓝色的会返回真
天际会返回错误

【问题讨论】:

  • 你使用的是什么版本的 PHP?

标签: php


【解决方案1】:

超级简短的示例,但这是我在没有 Regex 的情况下使用的方式。

$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.";

【讨论】:

【解决方案2】:

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

另一个想法是检查单词的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 )

当然,更好的解决方案是确定为什么不能使用正则表达式,因为这些解决方案的效率远不及模式搜索。

【讨论】:

  • 问题是——在处理非常大的文本时,它真的是最有效的方法吗?
  • @Lior 最有效的事情是弄清楚如何让正则表达式工作。这远没有那么高效。
  • 我这辈子都想不通......老实说,我不知道为什么它不起作用,不能再等了,不幸的是我有使用其他解决方案。
【解决方案3】:

如果您只是想查找一个单词是否在字符串中,您可以将字符串存储在变量中(如果打印字符串,则打印带有字符串的变量)并使用“in”。示例:

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

【讨论】:

    猜你喜欢
    • 2011-12-11
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多