Skip to content
Advertisement

What’s the fastest way to find and replace in PHP?

I need a way of replacing some variables within a passed string.

Example:

I pass through “#fname# jumped over the tall wall to get his phone with the number #phone#”.

I need the string to be replaced with “John jumped over the tall wall to get his phone with the number 0123456789”.

I have used str_replace in the past but they is alot of tags (#example#) to be replaced per execution – 1000+, and i am wary of speed performance..

Maybe a regex with preg_replace? The language is PHP.

Thank you.

Kyle

Advertisement

Answer

Well, you can use arrays with str_replace:

So, let’s say you had these tags to replace:

JavaScript

And you wanted to use this data:

JavaScript

And you had a list of strings you wanted to do it in:

JavaScript

You could call:

JavaScript

Which would result in:

JavaScript

So you can do a lot in one shot, and it should be much faster than doing anything with a regex for this kind of operation (REGEX could be better if you wanted multiple replaces for each tag, eg: array('#firstname#', '#fname#', '#givenname#', '#gname#') all for first name…)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement