從字符串的開頭刪除一個字符串

[英]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.

使用str_replace(),它將刪除所有的bla_'s。

8 个解决方案

#1


250  

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)

拍攝時間:0.0369毫秒(0.000,036,954秒)

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.

拍攝時間:0.1749 ms(0.000174999秒)第一遍(編譯),0.0510 ms(0.000051021秒)。

Profiled on my server, obviously.

顯然是在我的服務器上。

#2


43  

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

您可以使用正則表達式的插入符(^)錨匹配字符串的開始:

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

#3


11  

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

#4


4  

Here.

在這里。

$array = explode("_", $string);
if($array[0] == "bla") array_shift($array);
$string = implode("_", $array);

#5


0  

<?php
$str = 'bla_string_bla_bla_bla';
echo preg_replace('/bla_/', '', $str, 1); 
?>

#6


0  

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

我認為substr_replace滿足您的需要,您可以將替換限制為字符串的一部分:http://nl3.php.net/manual/en/function.substr-replace.php(這將使您只看到字符串的開頭)。

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.

您可以使用str_replace的count參數(http://nl3.php.net/manual/en/function.str-replace.php),這將允許您從左邊開始限制替換的數量,但不會強制它在開始時執行。

#7


-5  

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

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

now does what you want.

現在做你想做的。

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

#8


-6  

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

刪除www。從字符串開始,這是最簡單的方法(ltrim)

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2010/12/23/ba1644c3eefeac8a6ce30f2e2f62a304.html



 
  © 2014-2022 ITdaan.com 联系我们: