Skip to main content

preg_match() vs strpos() Performances in PHP

There are two ways to check if a string contains another string in PHP. The first one is using the preg_match() function and the second one is using the strpos() and strstr() function. In this article, we’re going to compare the performances of these two functions to see which one is faster.

It is recommended to avoid using regular expressions in PHP, as they can be slow and resource-intensive. The strpos() or strstr() function is a much faster alternative and is generally more than adequate for most purposes.

If you want to profiling the performance yourself, use the following snippet.

To compare the performances of these two functions, we’re going to use the microtime() function. This function returns the current time in microseconds. We’re going to call this function before and after each function to see how long each function takes to execute.

Here’s the code that we’re going to use:

$time_start = microtime(true);

for ($i = 0; $i < 100000; $i++) {
    preg_match('/abc/', 'abcdefabc');
}


$time_end = microtime(true);
$time = $time_end - $time_start;
echo "preg_match(): $time <br/><br/><br/>";


$time_start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    strpos('abcdefabc', 'abc');
}

$time_end = microtime(true);
$time = $time_end - $time_start;
echo "strpos(): $time\n";

And here are the results:

  • preg_match(): 0.0075819492340088
  • strpos(): 0.0036470890045166

As you can see, the preg_match() function is about twice slower than the strpos() function.

So, if you’re looking for a fast way to check if a string contains another string in PHP, the strpos() or strstr() function is the way to go.

By continuing to use the site, you agree to the use of cookies.