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:

$search = array(
    '#firstname#',
    '#lastname#',
    '#phone#',
    '#foobar',
);

And you wanted to use this data:

$replace = array(
    'John',
    'Doe',
    '5555553535',
    'baz',
);

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

$strings = array(
    'My First Name is: #firstname#',
    'My Last Name is: #lastname#',
    'My Contact Info Is: #phone#, #foobar#',
);

You could call:

$populatedStrings = str_replace($search, $replace, $strings);

Which would result in:

array(
    'My First Name is: John',
    'My Last Name is: Doe',
    'My Contact Info Is: 5555555353, baz',
);

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