Remove a string from the beginning of a string

I have a string that looks like this:

$str = "bla_string_bla_bla_bla";

How can I remove the first bla_; but only if it's found at the beginning of the string?

With str_replace(), it removes all bla_'s.


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, '/') . '/', '', $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.


You can use regular expressions with the caret symbol (^) which anchors the match to the beginning of the string:

$str = preg_replace('/^bla_/', '', $str);

function remove_prefix($text, $prefix) {
    if(0 === strpos($text, $prefix))
        $text = substr($text, strlen($prefix)).'';
    return $text;
}