Manatok
Manatok

Reputation: 5696

str_replace alternative for PHP

In the str_replace manual for PHP it states the following:

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

Is there an equivalent function that does not have this gotcha or how can I safely do this?

Upvotes: 5

Views: 7670

Answers (2)

Vyktor
Vyktor

Reputation: 20997

You're looking for strtr ( string $str , array $replace_pairs ).

If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

Example from the manual:

<?php
$trans = array("h" => "-", "hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>

Will output:

hello all, I said hi

Which should be exactly what you need.

Upvotes: 14

Tarang
Tarang

Reputation: 75945

Use preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) im pretty sure you could make it replace all the values or one if thats what you're asking.

Or you could do it in pieces if theres an order to replace what you want

$value = preg_replace($pattern1, '..', $value);
$value = preg_replace($pattern2, '..', $value);
$value = preg_replace($pattern3, '..', $value);

Upvotes: 0

Related Questions