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\");");
?>
Related
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 have a function for dumping variables on the screen and what I'd like to do is to show the name of the variable next to the value of the variable, so it would output something like this:
function my_function($var) {
return '<pre>' . var_dump($var) . '</pre>';
}
$myVar = 'This is a variable';
echo my_function($var); // outputs on screen: myVar has value: This is a variable
$anotherVar = 'Something else';
echo my_function($anotherVar); // outputs on screen: anotherVar has value: Something else
How can I do this ?
PHP offers no simple way of doing this. The PHP developers never saw any reason why this should be neccesary.
You can however use a couple of workarounds found here:
Is there a way to get the name of a variable? PHP - Reflection and here: How to get a variable name as a string in PHP?
Probably, debug_backtrace() function in such case will be the most effective:
function my_function($var) {
$caller = debug_backtrace()[0];
$file = $caller['file'];
$lineno = $caller['line'];
$fp = fopen($file, 'r');
$line = "";
for ($i = 0; $i < $lineno; $i++) {
$line = fgets($fp);
}
$regex = '/'.__FUNCTION__.'\(([^)]*)\)/';
preg_match($regex, $line, $matches);
echo '<pre>'. $matches[1]. ": $var</pre>";
}
$anotherVar = 'Something else';
my_function($anotherVar);
// output: $anotherVar: Something else
I a stuck with regular expression and i need help.
So basically i want to do somethning like this:
$data = "hi";
$number = 4;
$reg = '/^[a-z"]{1,4}$/';
if(preg_match($reg,$data)) {
echo 'Match';
}else {
echo 'No match';
}
But i want to use variable
$reg = '/^[a-z"]{1, variable here }$/';
I have tried:
$reg = '/^[a-z"]{1, '. $number .'}$/';
$reg = "/^[a-z\"]{1, $number}$/";
But not getting right result.
Tnx for help
In the first example you have space where you shouldn't have one,
you have:
$reg = '/^[a-z"]{1, '. $number .'}$/';
your should have:
$reg = '/^[a-z"]{1,'. $number .'}$/';
then it works just fine
Update: You have same error in second example - thanks to AbraCadaver
Another way to use variables in regex is through the use of sprintf.
For example:
$nonWhiteSpace = "^\s";
$pattern = sprintf("/[%s]{1,10}/",$nonWhiteSpace);
var_dump($pattern); //gives you /[^\s]{1,10}/
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]
I'm fairly new to coding and just recently started working on integrating functions into my PHP. I am trying to encode and echo an IP address to Google Analytics's. This is what my custom modifier looks like:
pagetracker._setCustomVar(1, "IP", "<?php include function.php; echo remove_numbers_advanced($_SERVER['REMOTE_ADDR']); ?>", 2);
The function file looks like this:
<?
function remove_numbers_advanced($string)
{
$numbers = array();
for($counter =0; $counter <= 10; $counter++) {
$numbers[$counter] = $counter;
$replacements = array("A","7","B","6","C","4","D","3","E","F");
$string = str_replace($numbers, $replacements, $string);
return $string;
}';
echo remove_numbers_advanced($string);
?>
When I isolated the PHP section of my custom variable in an attempt to test it the page throws a 500 error, suggesting to me that there is something wrong with how I have my script set up.
Please bear in mind I am rather new to this so simple terms and examples would help a ton!
There are few errors in your function. The correct function is:
function remove_numbers_advanced($string)
{
$numbers = array();
for($counter =0; $counter <= 10; $counter++)
$numbers[$counter] = $counter;
$replacements = array("A","7","B","6","C","4","D","3","E","F");
$string = str_replace($numbers, $replacements, $string);
return $string;
}
1- You added open curly braces next to for loop but did not close it
2- Also there is " '; " at the closing braces of function. It shouldn't be there.
include function must have a string parameter so put '' around file name
pagetracker._setCustomVar(1, "IP", "<?php include 'function.php'; echo remove_numbers_advanced($_SERVER['REMOTE_ADDR']); ?>", 2);