I have a script where I can use either substr()
or str_replace()
. With substr()
I just have to cut off the last character and with str_replace I need to replace !
with nothing. Which one would be faster?
I guess substr()
?
As expected, the substring is fastest because: It avoids compiling a regular expression.
The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.
The str_replace() is a built-in function in PHP and is used to replace all the occurrences of the search string or array of search strings by replacement string or array of replacement strings in the given string or array respectively.
The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.
I'm not familiar with the PHP source code, but I assume definitely substr()
, as it can jump directly to the defined offset.
Don't forget though that this will make a difference only with lots of data. For smaller strings, it is preferable to choose whatever makes for more readable code.
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