To remove a substring from a string, call the replace() method, passing it the substring and an empty string as parameters, e.g. str. replace("example", "") . The replace() method will return a new string, where the first occurrence of the supplied substring is removed.
Use the . strip() method to remove whitespace and characters from the beginning and the end of a string. Use the . lstrip() method to remove whitespace and characters only from the beginning of a string.
In Python you can use the replace() and translate() methods to specify which characters you want to remove from a string and return a new modified string result. It is important to remember that the original string will not be altered because strings are immutable.
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.
You can use regular expressions with the caret symbol (^
) which anchors the match to the beginning of the string:
$str = preg_replace('/^bla_/', '', $str);
function remove_prefix($text, $prefix) {
if(0 === strpos($text, $prefix))
$text = substr($text, strlen($prefix)).'';
return $text;
}
Here.
$array = explode("_", $string);
if($array[0] == "bla") array_shift($array);
$string = implode("_", $array);
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With