Remove a string from the beginning of a string

后端 未结 11 1920
忘了有多久
忘了有多久 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:09

    str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

    now does what you want.

    $str = "bla_string_bla_bla_bla";
    str_replace("bla_","",$str,1);
    
    0 讨论(0)
  • 2020-11-28 07:18

    Here's an even faster approach:

    // strpos is faster than an unnecessary substr() and is built just for that 
    if (strpos($str, $prefix) === 0) $str = substr($str, strlen($prefix));
    
    0 讨论(0)
  • 2020-11-28 07:19

    Nice speed, but this is hard-coded to depend on the needle ending with _. Is there a general version? – toddmo Jun 29 at 23:26

    A general version:

    $parts = explode($start, $full, 2);
    if ($parts[0] === '') {
        $end = $parts[1];
    } else {
        $fail = true;
    }
    

    Some benchmarks:

    <?php
    
    $iters = 100000;
    $start = "/aaaaaaa/bbbbbbbbbb";
    $full = "/aaaaaaa/bbbbbbbbbb/cccccccccc/ffffdffffdffffdd/eeeeeeeeee";
    $end = '';
    
    $fail = false;
    
    $t0 = microtime(true);
    for ($i = 0; $i < $iters; $i++) {
        if (strpos($full, $start) === 0) {
            $end = substr($full, strlen($start));
        } else {
            $fail = true;
        }
    }
    $t = microtime(true) - $t0;
    printf("%16s : %f s\n", "strpos+strlen", $t);
    
    $t0 = microtime(true);
    for ($i = 0; $i < $iters; $i++) {
        $parts = explode($start, $full, 2);
        if ($parts[0] === '') {
            $end = $parts[1];
        } else {
            $fail = true;
        }
    }
    $t = microtime(true) - $t0;
    printf("%16s : %f s\n", "explode", $t);
    

    On my quite old home PC:

    $ php bench.php
    

    Outputs:

       strpos+strlen : 0.158388 s
             explode : 0.126772 s
    
    0 讨论(0)
  • 2020-11-28 07:20
    function remove_prefix($text, $prefix) {
        if(0 === strpos($text, $prefix))
            $text = substr($text, strlen($prefix)).'';
        return $text;
    }
    
    0 讨论(0)
  • 2020-11-28 07:20

    Remove www. from beginning of string, this is the easiest way (ltrim)

    $a="www.google.com";
    echo ltrim($a, "www.");
    
    0 讨论(0)
  • 2020-11-28 07:24

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

    $str = preg_replace('/^bla_/', '', $str);
    
    0 讨论(0)
提交回复
热议问题