Remove a string from the beginning of a string

后端 未结 11 1921
忘了有多久
忘了有多久 2020-11-28 06:30

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 fo

相关标签:
11条回答
  • 2020-11-28 07:26
    <?php
    $str = 'bla_string_bla_bla_bla';
    echo preg_replace('/bla_/', '', $str, 1); 
    ?>
    
    0 讨论(0)
  • 2020-11-28 07:32

    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.

    0 讨论(0)
  • This will remove first match wherever it is found i.e., start or middle or end.

    $str = substr($str, 0, strpos($str, $prefix)).substr($str, strpos($str, $prefix)+strlen($prefix));
    
    0 讨论(0)
  • 2020-11-28 07:34

    I think substr_replace does what you want, where you can limit your replace to part of your string: http://nl3.php.net/manual/en/function.substr-replace.php (This will enable you to only look at the beginning of the string.)

    You could use the count parameter of str_replace ( http://nl3.php.net/manual/en/function.str-replace.php ), this will allow you to limit the number of replacements, starting from the left, but it will not enforce it to be at the beginning.

    0 讨论(0)
  • 2020-11-28 07:36

    Here.

    $array = explode("_", $string);
    if($array[0] == "bla") array_shift($array);
    $string = implode("_", $array);
    
    0 讨论(0)
提交回复
热议问题