Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to replace string patterns by mask

Tags:

php

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
like image 846
user1996959 Avatar asked Jan 21 '13 12:01

user1996959


People also ask

How do you replace all characters in a string?

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.

What is Regex in str replace?

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.

How replace all occurrences of a string in TypeScript?

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 .


2 Answers

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

like image 64
Jeroen Avatar answered Sep 19 '22 13:09

Jeroen


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.

like image 45
WakeupMorning Avatar answered Sep 17 '22 13:09

WakeupMorning