Replace mustache placeholder using data from an associative array [duplicate] - php

This question already has answers here:
what is the efficient way to parse a template like this in php?
(3 answers)
str_replace() with associative array
(5 answers)
PHP - Replacing multiple sets of placeholders while looping through arrays
(1 answer)
How do I use preg_replace in PHP with {{ mustache }}
(1 answer)
How can I replace a variable in a string with the value in PHP?
(13 answers)
Closed 19 days ago.
How to write custom php function for replacing variable with value by passing function parameters?
$template = "Hello, {{name}}!";
$data = [
'name'=> 'world'
];
echo replace($template, $data);
function replace($template, $data) {
$name = $data['name'];
return $template;
}
echo replace($template, $data); must return "Hello, world!"
Thank You!

One way would be to use the built-in str_replace function, like this:
foreach($data as $key => $value) {
$template = str_replace("{{$key}}", $value, $template);
}
return $template;
This loops your data-array and replaces the keys with your values. Another approach would be RegEx

You can do it using preg_replace_callback_array to Perform a regular expression search and replace using callbacks.
This solution is working for multi variables, its parse the entire text, and exchange every indicated variable.
function replacer($source, $arrayWords) {
return preg_replace_callback_array(
[
'/({{([^{}]+)}})/' => function($matches) use ($arrayWords) {
if (isset($arrayWords[$matches[2]])) $returnWord = $arrayWords[$matches[2]];
else $returnWord = $matches[2];
return $returnWord;
},
],
$source);
}
demo here

Related

php parsing a basic string contained in a variable [duplicate]

This question already has answers here:
Split a comma-delimited string into an array?
(8 answers)
Closed 7 years ago.
I'm new to php and have a basic question regarding parsing strings.
I have a variable "SKU" whose value is "9897_BLK"
I need to split this into two separate values:
"STYLE" with a value of "9897" AND "COLOR" with a value of "BLK"
I suppose there's a way to use the underscore to delimit the string.
Thanks for your help.
Try explode. This basically separates your string using a delimiter as your first parameter, and the string as the second parameter and returns an array of strings generated. Afterwards you can check if the string was properly parsed or you can just directly assign values just like the one below:
$sku = "9897_BLK";
$sku_parsed = explode("_", $sku);
$style = $sku_parsed[0];
$color = $sku_parsed[1];
If you want more details, the PHP manual is very accessible and has in-depth examples and use-cases for various scenario.
http://php.net/manual/en/function.explode.php
Try this:
$sku = "9897_BLK";
list($style, $color) = explode("_", trim($sku));
In PHP we use an function to split any string with delimiter.
You may try the explode function. The explode function return an array as output and the array values are the delimited values respectively.
Here is code snippet:
$SKU = "9897_BLK";
$DELIMITED_ARRAY = explode("_", $SKU);
$STYLE = $DELIMITED_ARRAY[0];
$COLOR = $DELIMITED_ARRAY[1];

Remove everything right of a match in a variable in PHP [duplicate]

This question already has answers here:
PHP remove all characters before specific string
(4 answers)
Closed 8 years ago.
How can I remove everything before the first ABC in a string?
So that this:
somethingrandomABCotherrandomstuffABCmorerandomstuffABC
turns to this:
otherrandomstuffABCmorerandomstuffABC.
Is this possible with php?
There is a php built in for doing this: strstr
Combine with substr to strip out your token:
$out = substr(strstr($text, 'ABC'), strlen('ABC'))
<?php
function removeEverythingBefore($in, $before) {
$pos = strpos($in, $before);
return $pos !== FALSE
? substr($in, $pos + strlen($before), strlen($in))
: "";
}
echo(removeEverythingBefore("somethingrandomABCotherrandomstuffABCmorerandomstuffABC", "ABC"));
?>
Outputs:
otherrandomstuffABCmorerandomstuffABC

partial match in a PHP in_array() [duplicate]

This question already has answers here:
Search in array with relevance
(5 answers)
Closed 9 years ago.
I am trying to search an array for a list of words(areas).
But sometime the word(area) in the array is 2 words.
i.e in the array is "Milton Keynes" so "Milton" is not being matched
Is there any way i can do this, without splitting any double words in the array (as i assume this will be a big load on the server)
Below is an example of what i am doing
foreach (preg_split("/(\s)|(\/)|(\W)/", $words) as $word){
if (in_array($word, $areaArray)){
$AreaID[] = array_search($word, $areaArray);
}
}
Grateful, as always for any advice!
You could use preg_grep():
$re = sprintf('/\b%s\b/', preg_quote($search, '/'));
// ...
if (preg_grep($re, $areaArray)) {
// we have a match
}
You can opt to make the match case insensitive by adding the /i modifier.
You can use regular expression to find a value, this will work similar to MySQL like function
$search='Milton Keynes';
foreach ($areaArray as $key => $value) {
if (preg_match('~'.preg_quote($search).'~i',$value)) {
echo "$key";
}
}

converting from a string to a variable in php [duplicate]

This question already has answers here:
How to expand variables in a string
(7 answers)
Closed 8 years ago.
I have written this,
<?php
function get_pounds($var){
$string ='i have $var pounds';
return $string;
}
$v =100;
echo get_pounds($v);
?>
outputs:
i have $var pounds
I know I can use "" or $string ='i have'. $var .'pounds'; to avoid this problem. But take a situation when fetching string from a database. I want it to parse it and make $var as a variable on its own without being part of the string.
say
variable
I have $var pounds
My query goes "select variable from $table;"
return mysql_query($query);
This will return a string.
How do I parse it so that my $var is not parsed as a var ?
instead of $string ='i have $var pounds'; try $string ="i have $var pounds";

Matching words in strings [duplicate]

This question already has answers here:
Php compare strings and return common values
(3 answers)
Closed 8 years ago.
I have two strings of keywords
$keystring1 = "tech,php,radio,love";
$keystring2 = "Mtn,huntung,php,tv,tech";
How do i do return keywords that common in both strings
You can do this:
$common = array_intersect(explode(",", $keystring1), explode(",", $keystring2));
If you want them back into strings, you can just implode it back.
Hmm, interesting question... You can use this.
$arr1 = explode(',',$keystring1);
$arr2 = explode(',',$keystring2);
$duplicates = array_intersect($arr1,$arr2);
foreach($duplicates as $word) {
echo $word;
}
You could explode() both strings on commas into arrays and loop through the first array checking to see if any of the words exist in the second array using the in_array() function. If so then add that word to a "common words" array.
Those are going to need to be arrays not variables.
$keystring1 = array('tech','php','radio','love');
$keystring2 = array('mtn','huntung','php','tv','tech');
First of all...

Categories