phpstringprefix

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.


Solution

  • 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.