190

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.

1

10 Answers 10

397

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.

14
  • 8
    I've never seen the ternary operator abused so badly, a simple if(condition) { statement } would have been so much clearer. Dec 23, 2010 at 9:24
  • 56
    @salathe, I don't get it. Both idiomatic and regex-based solutions were proposed: comparing the two in terms of efficiency helps finding the best (again in terms of efficiency) answer. Why is that evil? Dec 23, 2010 at 9:41
  • 8
    @cbrandolino, no-one said it was evil. I just thought it entirely irrelevant to the question; much like "here are two solutions, and here's a picture of some kittens for more upvotes" would be.
    – salathe
    Dec 23, 2010 at 10:32
  • 9
    @salathe The kittens would not be relevant at all, the profiling (marginally) is. He didn't even weighted the answer based on his profiling, just added it objectively. That being said, given two identical answers, one with kittens, one without; I'd upvote the kittens, who wouldn't? :P
    – xDaizu
    Feb 19, 2016 at 9:15
  • 12
    if (substr($str, 0, strlen($prefix)) == $prefix) can be changed for if (0 === strpos($str, $prefix)) to avoid unnecessary memory allocation while keeping the same readability :)
    – xDaizu
    Feb 1, 2017 at 9:17
83

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

$str = preg_replace('/^bla_/', '', $str);
6
  • I wonder if it works faster than substr() version... I guess it does, and should be marked as proper answer. Nov 4, 2017 at 17:19
  • except it must be preg_quote'd
    – vp_arth
    Apr 20, 2018 at 8:53
  • 2
    I think this is much less painful to the eyes of a programmer and more intuitive. Even if it loses in performance to another suggested solution (which I really doubt), I'd still prefer this.
    – Fr0zenFyr
    Jul 11, 2019 at 6:02
  • multibyte nightmare is another issue with other solutions while this works well if the encoding of the file is correct. Anyway, it shouldn't be in the scope of this question so I wouldn't care.
    – Fr0zenFyr
    Jul 11, 2019 at 6:04
  • Came back to mention that this has an additional benefit of working with an array of subject strings. substr and strpos can't accept an array. There you go, a definite performance gain if you are dealing with an array. Cheers!
    – Fr0zenFyr
    Jul 11, 2019 at 8:07
28
function remove_prefix($text, $prefix) {
    if(0 === strpos($text, $prefix))
        $text = substr($text, strlen($prefix)).'';
    return $text;
}
2
  • 16
    The .'' isn't needed.
    – NateS
    Nov 11, 2014 at 14:33
  • 1
    For what it's worth since every one seems to be micro-optimizing here, this one is consistently fastest by my count. 1 million iterations came in at .17 sec, whereas (substr($str, 0, strlen($prefix)) == $prefix) from the accepted answer was more like .37 Jul 31, 2015 at 5:33
7

In PHP 8+ we can simplify using the str_starts_with() function:

$str = "bla_string_bla_bla_bla";
$prefix = "bla_";
if (str_starts_with($str, $prefix)) {
  $str = substr($str, strlen($prefix));
}

https://www.php.net/manual/en/function.str-starts-with.php

EDIT: Fixed a typo (closing bracket) in the example code.

6

Here.

$array = explode("_", $string);
if($array[0] == "bla") array_shift($array);
$string = implode("_", $array);
3
  • 2
    Measure 0.0000459153 seconds :)
    – Fabio Mora
    Dec 23, 2010 at 9:18
  • Nice speed, but this is hard-coded to depend on the needle ending with _. Is there a general version?
    – toddmo
    Jun 29, 2018 at 23:26
  • 1
    I would not use explode(), but if you have to, then you should use its limit parameter. This answer is missing its educational explanation. Mar 18, 2021 at 22:35
6

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));
2

Lots of different answers here. All seemingly based on string analysis. Here is my take on this using PHP explode to break up the string into an array of exactly two values and cleanly returning only the second value:

$str = "bla_string_bla_bla_bla";
$str_parts = explode('bla_', $str, 2);
$str_parts = array_filter($str_parts);
$final = array_shift($str_parts);
echo $final;

Output will be:

string_bla_bla_bla
1

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/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);

On my quite old home PC:

$ php bench.php

Outputs:

   strpos+strlen : 0.158388 s
         explode : 0.126772 s
1

Symfony users can install the string component and use trimPrefix()

u('file-image-0001.png')->trimPrefix('file-');           // 'image-0001.png'
-1

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.

2
  • 1
    substr_replace will replace the characters in the given range regardless of whether they’re the prefix you want to remove or something else. The OP wants to remove bla_ “only if it's found at the beginning of the string.” Mar 31, 2016 at 10:30
  • This answer is misleading and low-value. If you just wanted to drop links, you could have just offered a comment under the question. str_replace()'s count parameter DOES NOT allow you to limit the number of replacements. Nov 8, 2021 at 2:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.