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
<?php
$str = 'bla_string_bla_bla_bla';
echo preg_replace('/bla_/', '', $str, 1);
?>
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.
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));
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.
Here.
$array = explode("_", $string);
if($array[0] == "bla") array_shift($array);
$string = implode("_", $array);