the string looks like this:


what I want is to remove the first bla_ (only if it's found at the beginning of the string)

How can I do this? with str_replace() it removes all bla_'s

Accepted Answer

Plain form, without regex:

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';

if (substr($str, 0, strlen($prefix) ) == $prefix) {
    $str = substr($str, strlen($prefix), strlen($str) );

Takes: 0.0000369549 seconds

And with:

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

Takes: 0.0001749992 seconds the 1st run (compiling), and 0.0000510216 seconds after.

Profiled on my server, obviously.

Written by Fabio M.
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the community.
It is licensed under cc-wiki