access variable from string name - php

I have this variable
$foo['title'] = 'Hello World';
I want to access this variable from a string.
$string = '$foo["title"]';
How can I display "Hello World" by my variable $string?
I searched an other topic, i found something similar, unfortunately it doesn't work.
$foo['title'] = "Hello, world!";
$bar = "foo['title']";
echo $$bar;

Actually I am not sure I understand you goal.
Do you want maybe this?
$foo['title'] = "Hello, world!";
$bar = "$foo[title]";
echo $bar;
The result:
Hello, world!
This is the same as this:
$bar = $foo['title'];
Or you would like to prepend/append something? Like this:
$bar = 'prepend something ' . $foo['title'] . ' append something';

You need to split the argument to the array away from the variable name, and then enclose the variable name in curly braces. So:
// get array argument
$matches = array();
preg_match("/\['(?s)(.*)'\]/", $bar, $matches);
$array_arg = $matches[1];
// get variable name
$arr = explode("[", $string, 2);
$var_name = $arr[0];
// put it together
${$var_name}[$array_arg]

Related

PHP preg_replace string within variables

I am using PHP 7.2.4, I want to make a template engine project,
I try to use preg_replace to change the variable in the string,
the code is here:
<?php
$lang = array(
'hello' => 'Hello {$username}',
'error_info' => 'Error Information : {$message}',
'admin_denied' => '{$current_user} are not Administrator',
);
$username = 'Guest';
$current_user = 'Empty';
$message = 'You are not member !';
$new_string = preg_replace_callback('/\{(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/', 'test', $string);
function test($matches)
{
return '<?php echo '.$matches[1].'; ?>';
}
echo $new_string;
But it just show me
Hello , how are you?
It automatically remove the variable...
Update:
here is var_dump:
D:\Wamp\www\t.php:5:string 'Hello <?php echo $username; ?>, how are you?' (length=44)
You may use create an associative array with keys (your variables) and values (their values), and then capture the variable part after $ and use it to check in the preg_replace_callback callback function if there is a key named as the found capture. If yes, replace with the corresponding value, else, replace with the match to put it back where it was found.
Here is an example code in PHP:
$values = array('username'=>'AAAAAA', 'lastname'=>'Smith');
$string = 'Hello {$username}, how are you?';
$new_string = preg_replace_callback('/\{\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}/', function($m) use ($values) {
return 'Hello <?php echo ' . (!empty($values[$m[1]]) ? $values[$m[1]] : $m[0]) . '; ?>';
}, $string);
var_dump($new_string);
Output:
string(47) "Hello Hello <?php echo AAAAAA; ?>, how are you?"
Note the pattern charnge, I moved the parentheses after $:
\{\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}
^ ^
Actually, you may even shorten it to
\{\$([a-zA-Z_\x7f-\xff][\w\x7f-\xff]*)}
^^
Do you want something like this?
<?php
$string = 'Hello {$username}, how are you?';
$username = 'AAAAAA';
$new_string = preg_replace('/\{(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/', $username, $string);
echo $new_string;
The result is:
Hello AAAAAA, how are you?
The more simple way would be to just write
<?php
$username = 'AAAAAA';
$string = 'Hello '.$username.', how are you?';
I'm a fan of keeping it simple so I would use str_replace since it will also change all instances which may come in handy as you go forward.
$string = 'Hello {$username}, how are you?';
$username = 'AAAAAA';
echo str_replace('{$username}',$username,$string);

I am using ucwords function in php but it doesnt work for the strings like "T.m.traders" or "R.j.kumar".?

String that has to be converted
$bar = 'R.m.traders';
$bar = ucwords(strtolower($bar));
output should be
R.M.Traders
You need to add delemeter . also called custom delimeter. You can check here. Anyway try this:
<?php
$bar = 'R.m.traders';
$bar = ucwords(strtolower($bar), "."); //After dot(.) next letter will be in Capital.
echo $bar;
?>
Just Try this Hope it helps
$bar = str_replace('.', ' ', $bar);
$bar = ucwords(strtolower($bar));
$bar = str_replace(' ', '.', trim($bar));
ucwords should be doing the first letter caps. R.m.traders is consider single word. If you give R m traders means you will get R M Traders
Alter way:
$bar = 'R.m.traders';
$bar_array = explode('.',$bar);
if(!empty($bar_array)){
$temp = array();
foreach($bar_array as $bar_arr){
$temp[] = ucwords(strtolower($bar_arr));
}
$bar_array = $temp;
}
$bar = implode('.',$bar_array);
echo $bar;

Replace variable with its value inside HTML without <?php ?>

Here is the situation. I have 2 files
content.php
<?php $my_var = "this is a variable"; ?>
<h1> php{my_var} </h1>
index.php
<?php include "content.php" ?>
The result should be:
<h1>this is a variable</h1>
I know how to work with preg_replace_callback. But I don't know how can I change php{my_var} with the value of $my_var.
All the logic should happens inside the index.php.
Edit
index.php
function replace_pattern($match)
{
what should I write here
}
echo preg_replace_callback("/php\:\{(.*)\}/", "replace_pattern", $Content);
Edit 2
Variables are not declare in the global scope
Note the added question-mark in the regular expression to make it less greedy.
$my_var = 'Hello World!';
// Get all defined variables
$vars = get_defined_vars();
$callback = function($match) use ($vars)
{
$varname = $match[1];
if (isset($vars[$varname])) {
return $vars[$varname]; // or htmlspecialchars($vars[$varname]);
} else {
return $varname . ' (doesn\'t exists)';
}
};
echo preg_replace_callback("/php\:\{(.*?)\}/", $callback, $Content);
Demo: http://phpfiddle.org/main/code/ax15-bpyw
Try this:
$my_var = "this is a variable";
$string = '<h1> php{my_var} </h1>';
$pattern = '/php{(.*)}/i';
preg_match($pattern, $string, $match);
$varName = $match[1];
$newString= preg_replace($pattern, $$varName, $string);
echo $newString;
But, warning!
In this case, i assume, if the code is php{somethin}, then there should be a $something variable. I used dynamic variable name. If you want to use only $my_var then use like this:
$newString= preg_replace($pattern, $my_var, $string);

PHP dynamic string update with reference

Is there any way to do this:
$myVar = 2;
$str = "I'm number:".$myVar;
$myVar = 3;
echo $str;
output would be: "I'm number: 3";
I'd like to have a string where part of it would be like a pointer and its value would be set by the last modification to the referenced variable.
For instance even if I do this:
$myStr = "hi";
$myStrReference = &$myStr;
$dynamicStr = "bye ".$myStrReference;
$myStr = "bye";
echo $dynamicStr;
This will output "bye hi" but I'd like it to be "bye bye" due to the last change. I think the issue is when concatenating a pointer to a string the the pointer's value is the one used. As such, It's not possible to output the string using the value set after the concatenation.
Any ideas?
Update: the $dynamicStr will be appended to a $biggerString and at the end the $finalResult ($biggerString+$dynamicStr) will be echo to the user. Thus, my only option would be doing some kind of echo eval($finalResult) where $finalResult would have an echo($dynamicStr) inside and $dynamicStr='$myStr' (as suggested by Lawson), right?
Update:
$myVar = 2;
$str = function() use (&$myVar) {
return "I'm number $myVar";
};
$finalStr = "hi ".$str();
$myVar = 3;
echo $finalStr;
I'd like for this to ouput: "hi I'm number 3" instead of "hi I'm number 2"...but it doesn't.
The problem here is that once a variable gets assigned a value (a string in your case), its value doesn't change until it's modified again.
You could use an anonymous function to accomplish something similar:
$myVar = 2;
$str = function() use (&$myVar) {
return "I'm number $myVar";
};
echo $str(); // I'm number 2
$myVar = 3;
echo $str(); // I'm number 3
When the function gets assigned to $str it keeps the variable $myVar accessible from within. Calling it at any point in time will use the most recent value of $myVar.
Update
Regarding your last question, if you want to expand the string even more, you can create yet another wrapper:
$myVar = 2;
$str = function() use (&$myVar) {
return "I'm number $myVar";
};
$finalStr = function($str) {
return "hi " . $str();
}
$myVar = 3;
echo $finalStr($str);
This is a little simpler than I had before. The single quotes tell PHP not to convert the $myVar into a value yet.
<?php
$myVar = 2;
$str = 'I\'m number: $myVar';
$myVar = 3;
echo eval("echo(\"$str\");");
?>

Something like .= in PHP but adds data "Before" instead of "After"?

The code below adds lo after Hel, thus outputs Hello :
$foo = "Hel";
$bar = "lo";
$foo .= $bar;
echo $foo;
If I want to output loHel instead, without using echo $bar . $foo what would you guys do? Just curious if there's simpler way.
There is no equivalent of the inverse of .= (such as =.).
You therefore will have to do it the long hand way.
$foo .= $bar is the same as $foo = $foo . $bar;
so you would have to do
$foo = $bar . $foo;
You can do:
$bar .= $foo
echo $bar;
Alternatively you can use substr_replace to insert one string at the beginning of another as:
$foo = substr_replace($foo,$bar,0,0);
I don't think there is a shorthand way of doing this.
String operators in the PHP manual
$bar = "lo".$foo;
$foo=$bar
$bar .= $foo;
echo $bar; // Will output loHel
$foo .= $bar is just a short form for $foo = $foo . $bar.
Unfortunately there is nothing like a prepend operator in PHP. So you can't avoid using $foo = $bar . $foo.

Categories