Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which function is faster? substr() or str_replace()? [closed]

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()?

like image 297
Michiel Pater Avatar asked Mar 04 '11 12:03

Michiel Pater


People also ask

Is substring faster than replace?

As expected, the substring is fastest because: It avoids compiling a regular expression.

What does str_ replace() do?

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.

Which one is correct string function replace multiple occurrences in input string in php?

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.

How to remove part of a string php?

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.


1 Answers

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.

like image 59
Pekka Avatar answered Oct 02 '22 02:10

Pekka