【问题标题】:Using text file as pattern preg_match_all PHP使用文本文件作为模式 preg_match_all PHP
【发布时间】:2014-08-20 21:50:37
【问题描述】:
error:preg_match_all(): Compilation failed: nothing to repeat at offset 59

大家好,我正在尝试为客户制作一个单词过滤器,我遇到了我的代码女巫从文本文件中提取单词的问题,无法从我的文本文件中读取 $ 字符,mycode 在下面。

 $lines=array();
  $fp=fopen('/opt/lampp/htdocs/Comments/Classes/Bad.txt', 'r');
  while (!feof($fp))
  {
    $line=fgets($fp);
    //process line however you like
    $line=trim($line);
    //add to array
    $lines[] = preg_quote(trim($line));
  }
    fclose($fp);
    $string = Input::get('comments');
    $matches = array();
    $matchFound = preg_match_all(
      "/\b(" . implode("|", $lines) . ")\b/i", 
            $string, 
            $matches
          );
    if ($matchFound) {
      $this->addError("The following is not allowed please change it.");
      $words = array_unique($matches[0]);
      foreach($words as $word) {
        echo "<li>" . $word . "</li>";
      }
      echo "</ul>";
    }

【问题讨论】:

    标签: php regex pattern-matching preg-match preg-match-all


    【解决方案1】:

    在读取文本文件时在每一行使用preg_quote

    【讨论】:

      【解决方案2】:

      您可能正在插入包含正则表达式元字符的文本,并以它们实际上被视为元字符的方式插入它们。您需要 preg_quote() 要插入的文本以转义所有这些元字符。

      【讨论】:

      • 所以它看起来像这样 $line=trim(preg_quote($line));
      • 一旦被引用,不要以任何方式操作被引用的字符串。 trim() 不会做太多,但任何其他操作都可以撤消引用。修剪然后引用。
      • 我在那之后做了 preg_quote,它仍然没有搜索特殊字符我可能做错了我更新了上面的代码
      • 你有preg_quote($lines)$lines 是你的数组。所以你在字符串上下文中使用了一个数组,PHP 会礼貌地将该数组转换为文字词Array。试试$lines[] = preg_quote(trim($line))
      • 所以我回显了数组,发现数组中的行不是 $$ 它是 \$\$ 可能是因为我的清理函数 htmlentities(string)($string, ENT_QUOTES, 'UTF-8');
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      • 1970-01-01
      • 2019-12-02
      相关资源
      最近更新 更多