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
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);
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));
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
function remove_prefix($text, $prefix) {
if(0 === strpos($text, $prefix))
$text = substr($text, strlen($prefix)).'';
return $text;
}
Remove www. from beginning of string, this is the easiest way (ltrim)
$a="www.google.com";
echo ltrim($a, "www.");
You can use regular expressions with the caret symbol (^
) which anchors the match to the beginning of the string:
$str = preg_replace('/^bla_/', '', $str);