Remove a string from the beginning of a string

Plain form, without regex:

$prefix = 'bla_';
$str="bla_string_bla_bla_bla";

if (substr($str, 0, strlen($prefix)) == $prefix) {
    $str = substr($str, strlen($prefix));
} 

Takes: 0.0369 ms (0.000,036,954 seconds)

And with:

$prefix = 'bla_';
$str="bla_string_bla_bla_bla";
$str = preg_replace('/^' . preg_quote($prefix, "https://stackoverflow.com/") . "https://stackoverflow.com/", '', $str);

Takes: 0.1749 ms (0.000,174,999 seconds) the 1st run (compiling), and 0.0510 ms (0.000,051,021 seconds) after.

Profiled on my server, obviously.

Leave a Comment