I Want change all Strings starting with {" and ending with "} to a variable,
for example:
Hello {username}, -> to Hello $array['username']
Your Country is {country}, -> Your Country is $array['country']
But i get all strings text from database with one variable (Mysql) With $array['content']
What I Want:
str_replace("{$whatinhere}",$array['$copytohere'],$array['content']);
str_replace("{company}",$array['company'],$array['content']);
Use preg_replace_callback function
echo preg_replace_callback('~{(.+?)}~',
function($x) use ($array) { return isset($array[$x[1]]) ? $array[$x[1]] : ''; },
$array['content']);
I think you should try this...
$content = $array['content'];
$mainContent = str_replace('{username}', $array['username'], $content);
$mainContent = str_replace('{company}', $array['company'], $mainContent);
echo $mainContent;
As I understand the $array variable contains the placeholder key/value pairs and also the content. You can try following code for replacing all placeholder keys with their corresponding values:
foreach ($array as $key => $value) {
if ($key != "content") {
$array["content"] = str_replace("{" . $key . "}", $value, $array["content"]);
}
}
/** Print contents */
echo $array["content"];
Related
I have array of 3000 elements which are like this
Array[0]= 405adc92-cfad-4be6-9ad2-ca363eda4933
Array[1]= 405adc92-cfad-4be6-9ad2-ca363eda4933
And I need to pass a variable in a function which require only a single quote at the beginning. I tried a solution on web which is pasting single quote on beginning and end aswell .like this
function add_quotes($str) {
return sprintf("'%s'", $str);
}
$csv = implode(',', array_map('add_quotes', $a));
$myArray = explode(',', $csv);
echo gettype($myArray[1]);
so answer is like this
myArray[1]='405adc92-cfad-4be6-9ad2-ca363eda4933'
So what Could I do to get rid ?
could you not just add the ' at the beginning of each string, rather than first add too many of them and afterwards remove the wrongly placed?
foreach($myArray as $key => &$value) {
$value = "'" . $value;
}
or (may be more readable as not by-reference)
foreach($myArray as $key => $value) {
$myArray[$key] = "'" . $value;
}
You can use rtrim - http://uk1.php.net/manual/en/function.rtrim.php to achieve. The generic syntax is:
<?php
$foo = 'my string\'';
$bar = rtrim($foo, '\'');
var_dump($foo); //shows my string'
var_dump($bar); //shows my string
so in your case take the array values, then use rtrim($myArray['myKey'], '\'') - this should do it for you :)
How to extract values from string seperated by |
here is my string
$var='foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
i need to store
$foo=1478
$boo=7854
$ccc=74125
Of course every body would suggest the explode route:
$var = 'foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
foreach(array_filter(explode('|', $var)) as $e){
list($key, $value) = explode('=', $e);
${$key} = $value;
}
Also, another would be to convert pipes to ampersand, so that it can be interpreted with parse_str:
parse_str(str_replace('|', '&', $var), $data);
extract($data);
echo $foo;
Both would produce the same. I'd stay away with variable variables though, it choose to go with arrays.
Explode the string by | and you will get the different value as array which is separated by |. Now add the $ before each value and echo them to see what you want.
$var = 'foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
$arr = explode("|", $var);
$arr = array_filter($arr);
foreach($arr as $val){
echo "$".$val."<br/>";
}
You will get:
$foo=1478
$boo=7854
$bar=74125
$aaa=74125
$bbb=470
$ccc=74125
$ddd=1200
OR if you want to store them in the $foo variable and show only the value then do this:
$var = 'foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
$arr = explode("|", $var);
$arr = array_filter($arr);
foreach($arr as $val){
$sub = explode("=", $val);
$$sub[0] = $sub[1];
}
echo $foo; //1478
You can use PHP variable variable concept to achieve your objective:
Try this:
<?php
$var='foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
$vars=explode("|",$var);
foreach($vars as $key=>$value){
if(!empty($value)){
$varcol=explode("=",$value);
$varname=$varcol[0];
$varvalue=$varcol[1];
$$varname=$varvalue; //In this line we use $$ i.e. variable variable concept
}
}
echo $foo;
I hope this works for you....
You can use explode for | with array_filter to remove blank elements from array, and pass the result to array_map with a reference array.
Inside callback you need to explode again for = and store that in ref array.
there after use extract to create variables.
$var='foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
$result = array();
$x = array_map(function($arr) use(&$result) {
list($key, $value) = explode('=', $arr);
$result[$key] = $value;
return [$key => $value];
}, array_filter(explode('|', $var)));
extract($result);
Use explode function which can break your string.
$array = explode("|", $var);
print_r($array);
I need to pass parameter into inner tag, ex.
{exp:myplugin:func}
{last_year subject="xxx"}
{/last_year}
{/exp:myplugin:func}
How can I fetch that parameter in the function?
Here's a function I've written to return the parameters for a variable pair inside a template tag pair:
private function get_variable_parameters($tagData, $varName) {
$parameters = array();
if (strpos($tagData, LD."/".$varName.RD) !== FALSE) {
//### Closing variable tag exists ###
if (preg_match_all("/".LD.$varName."(.*?)".RD."(.*?)".LD."\/".$varName.RD."/s", $tagData, $matches)) {
for ($num = 0; $num < count($matches[0]); $num++){
$allParams = explode(" ", trim($matches[1][$num]));
foreach($allParams as $value) {
$value = str_replace(array('"', "'"), '', $value);
$param = explode("=", $value);
if (!empty($param[1]))
$parameters[$param[0]] = $param[1];
}
}
}
}
return $parameters;
}//### End of get_variable_parameters function ###
So from your example code in your func method:
$tagData = ee()->TMPL->tagdata;
$varParameters = $this->get_variable_parameters($tagData, "last_year");
echo $varParameters["subject"];
Looking back over my code though, I don't think it handles multiple use of the same variable pair inside the same loop, so if required may need to change this line:
$parameters[$param[0]] = $param[1];
to:
$parameters[$num][$param[0]] = $param[1];
And then work out what instance of the variable pairs inside the same loop. Untested though, probably needs more work!
below is the code I have created. My point here is to convert all strings inside the function argument.
For example, fname('variable1=value1&variable2=value2'); I need to convert variable1 & variable2 into ang variable as $variable1, $variable2 instead parsing a plain text. I found out eval() function is useful but it only takes one string which is the "variable1" and its value.
function addFunction($arg){
echo eval('return $'. $arg . ';');
}
addFunction('variable1=value1&variable2=value2');
Now the problem is I got this error "Parse error: syntax error, unexpected '=' in D:\xampp\htdocs...\index.php(7) : eval()'d code on line 1". But if I have only one variable and value inside the function argument it works perfect, but I need to have more parameters here. Is this possible to do this thing or is there any other way to count the parameters before it can be evaluated?
Thank you,
function addFunction($arg)
{
parse_str($arg, $args);
foreach ($args as $key => $val) {
echo $key , " --> " , $val, "\n";
}
}
addFunction('variable1=value1&variable2=value2');
Output
variable1 --> value1
variable2 --> value2
You can also use
function addFunction($arg)
{
parse_str($arg);
echo $variable2; // value2
}
addFunction('variable1=value1&variable2=value2');
You are trying to create a variable with this name:
$variable1=value1&variable2=value2
You need to explode it at the & to get just the desired future variable names.
function addFunction($arg){
echo eval('return $'. $arg . ';');
}
$string = 'variable1=value1&variable2=value2';
$array = explode('&', $string);
foreach($array as $part)
{
addFunction($part);
}
You can break a string up using the PHP explode function, and then use eval to evaluate each variable indepedently.
$myvars = explode ('$', 'variable1=value1&variable2=value2');
$myvars is then an array which you can parse and feed to eval as needed.
Perhaps you can use explode()?
$varArr = explode("&",$arg);
foreach ($varArr as $varKey=>$varVal) {
echo eval('return $'.$varKey.'='.$varVal.';');
}
You need split the $arg at & to get each variable and then again at = to get each variable and value.
$arg = 'variable1=value1&variable2=value2';
$vars = explode('&', $arg);
foreach ($vars as $var) {
$parts = explode("=", $var);
echo eval('return $'. $parts[0] . '='. $parts[1] . ';');
}
Something like this:
function addFunction($arg)
{
$varArr = explode("&",$arg);
$varResponse ="";
foreach ($varArr as $varKey=>$varVal) {
$varResponse = $varResponse."$".$varVal.";";
}
return $varResponse;
}
echo addFunction('variable1=value1&variable2=value2');
Saludos ;)
I have a string that looks like this "thing aaaa" and I'm using explode() to split the string into an array containing all the words that are separated by space. I execute something like this explode (" ", $string) .
I'm not sure why but the result is : ["thing","","","","aaaa"]; Does anyone have an idea why I get the three empty arrays in there ?
EDIT : This is the function that I'm using that in :
public function query_databases() {
$arguments_count = func_num_args();
$status = [];
$results = [];
$split =[];
if ($arguments_count > 0) {
$arguments = func_get_args();
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arguments));
foreach ($iterator as $key => $value) {
array_push($results, trim($value));
}
unset($value);
$filtered = $this->array_unique_values($results, "String");
foreach ($filtered as $key => $string) {
if (preg_match('/\s/',$string)) {
array_push($split, preg_split("/\s/", $string));
} else {
array_push($split, $string);
}
}
unset($string);
echo "Terms : ".json_encode($split)."<br>";
foreach ($filtered as $database) {
echo "Terms : ".json_encode()."<br>";
$_action = $this->get_database($database);
echo "Action : ".json_encode($_action)."<br>";
}
unset($database);
} else {
return "[ Databases | Query Databases [ Missing Arguments ] ]";
}
}
It might be something else that messes up the result ?!
If you are looking to create an array by spaces, you might want to consider preg_split:
preg_split("/\s+/","thing aaaa");
which gives you array ("thing","aaaa");
Taken from here.
try this:
$str = str_replace(" ", ",", $string);
explode(",",$str);
This way you can see if it is just the whitespace giving you the problem if you output 4 commas, it's because you have 4 whitespaces.
As #Barmar said, my trim() just removes all the space before and after the words, so that is why I had more values in the array than I should have had.
I found that this little snippet : preg_replace( '/\s+/', ' ', $value ) ; replacing my trim() would fix it :)