This question already has an answer here:
Replace templates in strings by array values
(1 answer)
Closed 6 years ago.
$str = "Hello {{name}} welcome to {{company_name}}";
$array = ['name' => 'max', 'company_name' => 'Stack Exchange'];
how to replace {{name}} and {{company_name}} using array value. any php function that return output like
Hello max welcome to Stack Exchange
First create a new array with your search fields, wrapped in curly braces:
$searchArray = array_map(function($value) {
return "{{" . $value . "}}";
}, array_keys($array));
Now you have an array with the tokens you are searching for, and you already have an array of values you want to replace the tokens with.
So just do a simple str_replace:
echo str_replace($searchArray, $array, $str);
Working example: https://3v4l.org/8tPZt
Here's a tidy little function put together:
function fillTemplate($templateString, array $searchReplaceArray) {
return str_replace(
array_map(function($value) { return "{{" . $value . "}}"; }, array_keys($searchReplaceArray)),
$searchReplaceArray,
$templateString
);
}
Now you can call it like this:
echo fillTemplate(
"Hello {{name}} welcome to {{company_name}}",
['name' => 'max', 'company_name' => 'Stack Exchange']
);
// Hello max welcome to Stack Exchange
Example: https://3v4l.org/rh0KX
Checkout this nice function of PHP: http://php.net/manual/de/function.strtr.php
You can find there examples and explanation of it.
$str = "Hello {{name}} welcome to {{company_name}}";
$array = ['{{name}}' => 'max', '{{company_name}}' => 'Stack Exchange'];
print strtr ($str, $array);
Related
This question already has answers here:
PHP replace multiple value using str_replace? [duplicate]
(3 answers)
Closed 1 year ago.
I have a string containing comma-separated numbers and I also have an associative array in PHP containing unique numbers. What I want to achieve is to create a new string that contains only the exact match replacements based on the array. Here is my code so far:
<?php
$replacements = array(
'12' => 'Volvo',
'13' => 'BMW',
'132' => 'Alfa Romea',
'156' => 'Honda',
'1536' => 'Tesla',
'2213' => 'Audi'
);
$str ="12,13,132,2213";
echo str_replace(array_keys($replacements), $replacements, $str);
?>
The only problem is that the output is this:
Volvo,BMW,BMW2,22BMW
instead of this:
Volvo,BMW,Alfa Romeo,Audi
How can I achieve exact match search and replace in this function? Is there a fastest PHP solution for this problem?
Thanks,
belf
Another one-liner. Combine explode the string keys, and flip it to serve as keys using array_flip, then finally, array_intersect_key to combine them by key. implode the remaining values combined:
$cars = implode(', ', array_intersect_key($replacements, array_flip(explode(',', $str))));
You may use this very simple, straight-forward, and easy to understand code:
$result = [];
foreach (explode(',', $str) as $id) {
$result[] = isset($replacements[$id]) ? $replacements[$id] : $id;
}
$str = implode(',', $result);
I am creating a word search but I want to rank them base on the highest existence of search keyword. I am trying to make a search if array 1 key exists inside array 2 long string and then order the array by total occurrence of array 1 in array 2.
Example input:
$arr = array(array("id" => 1,"title" => "Hello World", "body" => "Hi Jude All this is my content"),
array("id" => 2,"title" => "Hello World Boy", "body" => "Hi All this is my content Girl"),
array("id" => 3,"title" => "Hello Kids", "body" => "Hi All this is my content Kid"),
array("id" => 4,"title" => "Hello World Jude", "body" => "Hi All this is my content Jude"),
array("id" => 5,"title" => "Hello World Jude January", "body" => "Hi All this is my content Jan"),
array("id" => 6,"title" => "Hello World January June Lord", "body" => "Hi All this is my content Jan Jude Lord"));
$str = "Hello world January jude";
Desire output:
Array in order:
Hello World Jude January
Hello World Jude
Hello World January June Lord
Hello World
Hello World Boy
Hello Kids
I wrote a question earlier base on solving problem for Is there any PHP function to solve out array value matches in another array value string? afterward I got solution on that but my main problem now is that it is judging my filter base on case sensitivity if my search keyword is hello world and I have Hello world and hi world because the world on hi world is lowercase as the one at my search keywords it picks the one with the lowercase first before considering the one with the most matches I have tried several things but I could not get it.
Note: I want the Output to be returned the way it is not to return in lowercase format.
This is what I tried using the example input from above:
$arr2 = sort_most_exists_asc($arr, $str);
var_dump($arr2);
function sort_most_exists_asc($array, $str) {
usort($array, function ($a, $b) use ($str) {
$aa = count(array_intersect(explode(" ", $str), explode(" ", $a['title'])));
$bb = count(array_intersect(explode(" ", $str), explode(" ", $b['title'])));
return $bb - $aa;
});
return $array;
}
Worked well if its formatted exactly like that but I don't want it to follow case sensitivity during the array_intersect.
Solved working fine here for people who may need further help on something like this
https://3v4l.org/tlvbh.
I fixed the issue by using array-uintersect - which can take function as argument for compare. I send it strcasecmp - to avoid the case-sensitivity in the string compare.
This is my new sort function:
function sort_most_exists_asc($array, $str) {
usort($array, function ($a, $b) use ($str) {
$aa = count(array_uintersect(explode(" ", $str), explode(" ", $a['title']), 'strcasecmp'));
$bb = count(array_uintersect(explode(" ", $str), explode(" ", $b['title']), 'strcasecmp'));
return $bb - $aa;
});
return $array;
}
A few tips:
if you want to modify by reference (like php's other sort functions), throw a lamba (&) on the incoming function parameter and omit the return line.
in the interests of efficiency, don't explode the search string on each iteration -- explode it only once.
the spaceship operator is a great way to sort two arrays by length without explicit counting.
Code: (Demo)
function sort_most_needles(&$array, $str) {
$needles = explode(" ", $str);
usort($array, function ($a, $b) use ($needles) {
return array_uintersect($needles, explode(" ", $b['title']), 'strcasecmp')
<=>
array_uintersect($needles, explode(" ", $a['title']), 'strcasecmp');
});
}
sort_most_needles($arr, $str);
var_export($arr);
The equivalent effect with PHP7.4's arrow function syntax: (Demo)
function sort_most_needles(&$array, $str) {
$needles = explode(" ", $str);
usort($array,
fn($a, $b) =>
array_uintersect($needles, explode(" ", $b['title']), 'strcasecmp')
<=>
array_uintersect($needles, explode(" ", $a['title']), 'strcasecmp')
);
}
I have a template string like this
$myStr ="<font face=\"#3#\" size=\"6\">TEST STRING</font>";
And an array of fonts like this
$fontList = array(
0 => "ubuntumono",
1 => "opensans",
2 => "opensanscondensed",
3 => 'opensanslight',
4 => 'exo2',
5 => 'exo2light'
);
Now I want to check my string for face=\"#3#\" (3 is the index of font in $fontList)
and replace it with face=\"opensanslight\"
How can I do it with Regex & PHP? Thank you.
Assuming PHP 5.3.0 or better:
$myStr = preg_replace_callback('/#(\d+)#/', function ($matches) use ($fontList) {
return $fontList[$matches[1]];
}, $myStr);
Example
If you want to only change #number# when it is surrounded by quotes:
$myStr = preg_replace_callback('/"#(\d+)#"/', function ($matches) use ($fontList) {
return '"' . $fontList[$matches[1]] . '"';
}, $myStr);
Example
This question already has answers here:
Parse through a string php and replace substrings
(2 answers)
Closed 9 years ago.
OK, that's what I need :
Get all entries formatted like %%something%%, as given by the regex /%%([A-Za-z0-9\-]+)%%/i
Replace all instances with values from a table, given the index something.
E.g.
Replace %%something%% with $mytable['something'], etc.
If it was a regular replacement, I would definitely go for preg_replace, or even create an array of possible replacements... But what if I want to make it a bit more flexible...
Ideally, I'd want something like preg_replace($regex, $mytable["$1"], $str);, but obviously it doesn't look ok...
How should I go about this?
Code:
<?php
$myTable = array(
'one' => '1!',
'two' => '2!',
);
$str = '%%one%% %%two%% %%three%%';
$str = preg_replace_callback(
'#%%(.*?)%%#',
function ($matches) use ($myTable) {
if (isset($myTable[$matches[1]]))
return $myTable[$matches[1]];
else
return $matches[0];
},
$str
);
echo $str;
Result:
1! 2! %%three%%
if you don't want to tell upper from lower,
<?php
$myTable = array(
'onE' => '1!',
'Two' => '2!',
);
$str = '%%oNe%% %%twO%% %%three%%';
$str = preg_replace_callback(
'#%%(.*?)%%#',
function ($matches) use ($myTable) {
$flipped = array_flip($myTable);
foreach ($flipped as $v => $k) {
if (!strcasecmp($k, $matches[1]))
return $v;
}
return $matches[1];
},
$str
);
echo $str;
I want to enter some news into my website and enter a variable like %custom_heading% and get PHP to replace this with the custom heading I have set, this allows me to enter it in wherever I want, how would I go about doing this?
Update: Thanks this helped a lot :) Already in my code now.
Very simple use str_replace on the string...
$vars = array(
'name' => 'Joe',
'age' => 10
);
$str = 'Hello %name% you are %age% years old!';
foreach ($vars as $key => $value) {
$str = str_replace('%' . $key . '%', $value, $str);
}
echo $str; // Hello Joe you are 10 years old!