PHP: Subject String Length Limit of Regular Expression Matching Functions

by Yang Yang on December 12, 2009

Here’s a quick tip for those who have encountered this very same problem that all regular expression functions of PHP such as preg_match() and preg_replace() stop working when the input string (subject string to be searched or matched) is too long or large. If you believe your regular expressions should work but didn’t and the string to be searched is perhaps over 100kB in length, you have hit the match string length limit or PCRE’s backtracking limit set by configuration variable pcre.backtrack_limit.

To solve this issue and lift the length limit, to perhaps 10 times the original, you have to reset the default value of pcre.backtrack_limit in one of the following ways:

  1. If you are using cPanel, create a text file named php.ini and put it in the directory wherein you need to break the limit. Append this line in the file:
    pcre.backtrack_limit = 1000000
  2. If you operate your own dedicated / vps server, modify php.ini and put this line at the end of the file:
    pcre.backtrack_limit = 1000000
    Refer to this article to find out where your php.ini is.
  3. Use runtime configuration function ini_set() to set it at runtime:
    ini_set('pcre.backtrack_limit', 1000000)

This seems to be only affecting PHP 5.2.

Subscribe to Kavoir: blog feed

You should also read:

ctrtard January 20, 2011 at 12:26 pm

Hey great tip! You save me a bunch of time ;-)

Comments on this entry are closed.

Previous post:

Next post: