首页 文章

从字符串的开头删除一个字符串

提问于
浏览
115

我有一个看起来像这样的字符串:

$str = "bla_string_bla_bla_bla";

如何删除第一个 bla_ ;但只有在字符串的开头找到它?

使用 str_replace() ,它会删除所有 bla_ .

9 回答

  • 0

    普通形式,没有正则表达式:

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

    需要: 0.0369 ms (0.000,036,954秒)

    与:

    $prefix = 'bla_';
    $str = 'bla_string_bla_bla_bla';
    $str = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $str);
    

    需要: 0.1749 ms (0.000,174,999秒)第一次运行(编译)和 0.0510 ms (0.000,051,021秒)之后 .

    很明显,在我的服务器上描述 .

  • 47

    您可以使用具有插入符号( ^ )的正则表达式,该符号将匹配锚定到字符串的开头:

    $str = preg_replace('/^bla_/', '', $str);
    
  • 14
    function remove_prefix($text, $prefix) {
        if(0 === strpos($text, $prefix))
            $text = substr($text, strlen($prefix)).'';
        return $text;
    }
    
  • -7

    这里 .

    $array = explode("_", $string);
    if($array[0] == "bla") array_shift($array);
    $string = implode("_", $array);
    
  • -5
    <?php
    $str = 'bla_string_bla_bla_bla';
    echo preg_replace('/bla_/', '', $str, 1); 
    ?>
    
  • 0

    我认为substr_replace可以执行您想要的操作,您可以将替换限制为字符串的一部分:http://nl3.php.net/manual/en/function.substr-replace.php(这将使您只能查看字符串的开头 . )

    您可以使用str_replace(http://nl3.php.net/manual/en/function.str-replace.php)的count参数,这将允许您从左侧开始限制替换次数,但不会强制它在开头 .

  • 270

    速度不错,但是硬编码依赖于以_结尾的针 . 有通用版本吗? - 托德莫6月29日23:26

    一般版本:

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

    一些基准:

    <?php
    
    $iters = 100000;
    $start = "/aaaaaaa/bbbbbbbbbb";
    $full = "/aaaaaaa/bbbbbbbbbb/cccccccccc/dddddddddd/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);
    

    在我很老的家用电脑上:

    $ php bench.php
    

    输出:

    strpos+strlen : 0.158388 s
             explode : 0.126772 s
    
  • 0

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

    现在做你想要的 .

    $str = "bla_string_bla_bla_bla";
    str_replace("bla_","",$str,1);
    
  • 5

    删除www . 从字符串的开头,这是最简单的方法(ltrim)

    $a="www.google.com";
    echo ltrim($a, "www.");
    

相关问题