I have string like
$string = "string_key::%foo%:%bar%";
, and array of params
$params = array("foo" => 1, "bar" => 2);
How can I replace this params in $string pattern? Expected result is
string_key::1:2
To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.
The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match if any of the following conditions is true: If the replacement string cannot readily be specified by a regular expression replacement pattern.
To replace all occurrences of a string in TypeScript, use the replace() method, passing it a regular expression with the g (global search) flag. For example, str. replace(/old/g, 'new') returns a new string where all occurrences of old are replaced with new .
First, you need to rewrite the $params
array:
$string = "string_key::%foo%:%bar%";
$params = array("foo" => 1, "bar" => 2);
foreach($params as $key => $value) {
$search[] = "%" . $key . "%";
$replace[] = $value;
}
After that, you can simply pass the arrays to str_replace()
:
$output = str_replace($search, $replace, $string);
View output on Codepad
On a personal note, I did this one:
$string = "string_key::%foo%:%bar%";
$params = array("%foo%" => 1, "%bar%" => 2);
$output = strtr($string, $params);
You do not have to do anything else because if there is some value in the array or the string is not replaced and overlooked.
Fast and simple method for pattern replacement.
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