【问题标题】:PHP PCRE regex compilation errorPHP PCRE 正则表达式编译错误
【发布时间】:2011-12-08 15:48:11
【问题描述】:

当我尝试以下操作时:

$searchText = preg_quote($searchText, '/');
$remarks = preg_replace('/'.$searchText.'/i', '<span class="searchText">$0</span>', $remarks);

我收到以下错误消息:

正则表达式在偏移量 0 处太大

我不知道这意味着什么,为什么我会得到它或如何解决它。 当我用谷歌搜索此错误消息时,我得到了对我什至找不到的 php.ini 设置的引用。

【问题讨论】:

  • “太大”是一个非常明确的信息,也是当代语言中的常用短语 - 你确定你“没有任何线索”吗?
  • 显然你的正则表达式太大了。如果不了解该正则表达式是什么,我们将无法帮助您。
  • 我不明白为什么我的正则表达式会太大。上面的行在一次处理单个数据库记录的循环中。 $searchText 很小,用户输入的文本最多可能有十几个字符。 $remarks 来自一个 VARCHAR2(4000) 字段,所以我看不到它是如何超过 65,000 的,除非每次循环都需要设置一些东西。 $remarks 不会每次都通过循环连接。
  • 我还应该提到,当我添加 preg_quote() 行时问题就开始了。我补充说,因为一些用户正在输入正斜杠字符作为导致问题的搜索字符串的一部分。我知道 preg_quote() 会转义任何正则表达式特殊字符,但我看不出它如何将最多 4000 个字符的内容扩展到超过 65,000 个。

标签: php regex preg-replace


【解决方案1】:

正则表达式大小限制为 65539(是的,不是 65536)。您超出了限制。

请看这里:http://www.pcre.org/pcre.txt

SIZE AND OTHER LIMITATIONS

       There  are some size limitations in PCRE but it is hoped that they will
       never in practice be relevant.

       The maximum length of a compiled pattern is 65539 (sic) bytes  if  PCRE
       is compiled with the default internal linkage size of 2. If you want to
       process regular expressions that are truly enormous,  you  can  compile
       PCRE  with  an  internal linkage size of 3 or 4 (see the README file in
       the source distribution and the pcrebuild documentation  for  details).
       In  these  cases the limit is substantially larger.  However, the speed
       of execution is slower.

【讨论】:

  • 对我来说,“但希望它们在实践中永远不会相关”这句话翻译成“达到这个限制意味着你做错了什么”
【解决方案2】:

从之前的问题来看,您似乎正在尝试突出显示用户搜索的字词。如果是这样,您不需要正则表达式来执行此操作,您可以这样做:

$remarks = str_replace( $searchText, '<span class="searchText">' . $searchText . '</span>', $remarks);

请注意,它会突出显示单词中的字符串。如果您只想匹配整个单词,我可以更新我的答案。

【讨论】:

  • 我做 preg_replace() 的原因是因为我希望替换不区分大小写而不改变显示文本的大小写。我可以将您的 str_replace() 更改为 str_ireplace(),匹配并突出显示文本,而不管用户输入的文本是哪种情况,但返回给用户的结果的情况就是用户输入的任何情况。
猜你喜欢
  • 2014-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-25
  • 1970-01-01
  • 2023-03-20
相关资源
最近更新 更多