- Remove a string from the beginning of a string
- 10 Answers 10
- Php удалить первую букву строки
- Как удалить несколько элементов с начала строки!?
- Удаление первого элемента строки кириллица utf-8..
- Результат удаления первого элемента строки кириллица utf-8.
- How to remove the leading character from a string?
- Update
Remove a string from the beginning of a string
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.
10 Answers 10
$prefix = 'bla_'; $str = 'bla_string_bla_bla_bla'; if (substr($str, 0, strlen($prefix)) == $prefix)
Takes: 0.0369 ms (0.000,036,954 seconds)
$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.
I’ve never seen the ternary operator abused so badly, a simple if(condition) < statement >would have been so much clearer.
@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?
@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 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? 😛
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 🙂
You can use regular expressions with the caret symbol ( ^ ) which anchors the match to the beginning of the string:
$str = preg_replace('/^bla_/', '', $str);
I wonder if it works faster than substr() version. I guess it does, and should be marked as proper answer.
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.
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.
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!
function remove_prefix($text, $prefix)
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
$array = explode("_", $string); if($array[0] == "bla") array_shift($array); $string = implode("_", $array);
Nice speed, but this is hard-coded to depend on the needle ending with _ . Is there a general version?
I would not use explode() , but if you have to, then you should use its limit parameter. This answer is missing its educational explanation.
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));
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))
EDIT: Fixed a typo (closing bracket) in the example code.
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;
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
$parts = explode($start, $full, 2); if ($parts[0] === '') < $end = $parts[1]; >else
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);
strpos+strlen : 0.158388 s explode : 0.126772 s
Php удалить первую букву строки
В качестве первого примера мы будем использовать латиницу.
Для того, чтобы удалить первый элемент строки нужно в функцию substr в первом элементе записать строку, а во втором — количество элементов строки, которое вы хотите удалить. Поскольку у нас идет речь о первом элементе строки, то ставим 1.
Как удалить несколько элементов с начала строки!?
Предположим, что нам нужно не только удалить первый элемент/знак строки, а например несколько . , чтобы удалить несколько элементов строки с начала строки в функцию substr вторым элементом нужно указать количество требуемых знаков, которые вы хотите удалить!
Например мы хотим удалить три элемента с начала строки!
Удаление первого элемента строки кириллица utf-8..
Для удаления первого элемента/знака строки в utf-8 в кириллице, функция substr не сработает, потому, что количество символов в отличается, чтобы каждый раз — за разом не повторять сделаем страницу посвященную этой теме -> в utf-8 не работает!
В зависимости от настроек скрипта, настроек сервера нужно указать внутреннюю кодировку скрипта:
И для удаления первого элемента строки в кириллице UTF-8 нам нужна другая функция -> mb_substr
Результат удаления первого элемента строки кириллица utf-8.
Вы должны спросить! А что произойдет . если мы не укажем кодировку mb_internal_encoding — резонный вопрос!
Поэтому мы сделаем тоже самое только выше объявления этой кодировки и передадим данные в переменную и выведем с помощь. echo прямо здесь:
Результат: Как видим. вместо того, чтобы удалить первый элемент строки у нас какая-то кракозябра вылезла .
How to remove the leading character from a string?
The substr() function will probably help you here:
Strings are indexed starting from 0, and this functions second parameter takes the cutstart. So make that 1, and the first char is gone.
Be aware of unicode. If you’re dealing with an arbitrary string (e.g. «Ål
this is not a correct implementation, it not working with single character string «a». if you try single character string, substr return a boolean value
@anru The manual states if the string length is equal to the start parameter, an empty string will be returned. Prior to version 7, false was returned. So you would need to check if they’re equal if that is not the behaviour you want.
To remove every : from the beginning of a string, you can use ltrim:
$str = '::f:o:'; $str = ltrim($str, ':'); var_dump($str); //=> 'f:o:'
note that this is only intended for single characters. ltrim will trim all of the characters in the provided string: ltrim(‘prefixprefix_postfix’, ‘prefix’) results in ‘_postfix’;
«How to remove the first character of string in PHP» was the question and this comment doesn’t actually answer that.
$str = substr($str, 1); // this is a applepie :)
Exec time for the 3 answers :
Remove the first letter by replacing the case
$str = "hello"; $str[0] = ""; // $str[0] = false; // $str[0] = null; // replaced by �, but ok for echo
Exec time for 1.000.000 tests : 0.39602184295654 sec
Remove the first letter with substr()
$str = "hello"; $str = substr($str, 1);
Exec time for 1.000.000 tests : 5.153294801712 sec
Remove the first letter with ltrim()
$str = "hello"; $str= ltrim ($str,'h');
Exec time for 1.000.000 tests : 5.2393000125885 sec
Remove the first letter with preg_replace()
$str = "hello"; $str = preg_replace('/^./', '', $str);
Exec time for 1.000.000 tests : 6.8543920516968 sec
Thanks. See my update, though. It caused a problem for me when using the updated string in an SQL query.
I just tried the $str[0] = »; solution and it didn’t work. well it does however if you then plan on using the variable for example to compare > or < it won't work. It still counts ` ` as +` for example $str = 'hello'; $str[0] = ''; var_dump($str); // string(5) 'ello'
@Ian: I came across the same issue while fetching records from an API using a keyword, tried var_dump($keyword) which was showing the previous character length.. then I tried trimming the keyword and then it worked fine var_dump(trim($keyword)) .. Hope this helps someone.. 🙂
This does not work. The «removed» position is replaced with null byte, so you get «\0hello» instead of «hello».
works but will remove multiple : when there are more than one at the start.
will remove any character from the start.
if ($str[0] === ':') $str = substr($str, 1);
Update
After further tests, I don’t recommend using this any more. It caused a problem for me when using the updated string in a MySQL query, and changing to substr fixed the problem. I thought about deleting this answer, but comments suggest it is quicker somehow so someone might have a use for it. You may find trimming the updated string resolves string length issues.
Sometimes you don’t need a function:
$str = 'AHello'; $str[0] = ''; echo $str; // 'Hello'
This method modifies the existing string rather than creating another.