I've read through multiple tutorials on regex and it's associated functions but I am stumped on this one.
I have a really simple replace that looks for a specific delimiter and parses the name of a PHP variable. Here it is:
var_dump(preg_replace('/{{\$(.*?)}}/', ${$1}, $this->file));
I keep getting errors about php not liking the #1 in ${$1}. Fair enough, can't start a variable name with a number, I knew that...
So I tried:
var_dump(preg_replace('/{{\$(.*?)}}/', ${'$1'}, $this->file));
Same thing.
Yet if I try:
var_dump(preg_replace('/{{\$(.*?)}}/', '$1 yo', $this->file));
It works...
So, how do I get php to echo a variable named whatever $1 is.
For example:
$hola = yo;
$string = hello{{$hola}}hello{{$hola}};
var_dump(preg_replace('/{{\$(.*?)}}/', ${$1}, $string));
And the output would be:
helloyohelloyo
Spank you!
EDIT
I should also mention that I am aware that there is a standard recommendation on how to match php variables with regex, but i'd like to get it working with a regex that I fully understand first.
Like so:
$hola = 'yo';
$string = 'hello{{$hola}}hello{{$hola}}';
$result = preg_replace_callback('/\{\{\$(.*?)\}\}/', function ($matches) use ($hola) {
return ${$matches[1]};
}, $string);
var_dump($result);
preg_replace_callback calls a callback on every match.
In order to use the $hola variable inside the callback you need to explicitly make it available inside the function (use ($hola)).
All this said... I don't get it. What this code does is essentially what PHP already does out-of-the-box.
$hola = 'yo';
$string = "hello{$hola}hello{$hola}";
echo $string; // "helloyohelloyo"
Related
I'm working with the mailgun API and webhooks. Sometimes the message-id will include < and > but other times it wont.
In my controller, I am trying to check if the message-id contains < and > and if so then remove it and store that in a variable.
I may need to use rtrim or str_replace but I'm not sure if there is a better way to do this? Maybe regex?
Here is an example of one mailgun returns when the event is delivered:
<20180203002650.1.EEE3119CC37C5A82#domain.com>
Here is one when mailgun returns when the event is opened. (notice it is the same message ID now it does not contain < and >
20180203002650.1.EEE3119CC37C5A82#domain.com
Links:
Mailgun API,
rtrim,
str_replace
The trim function (to be exact, its overload that takes two arguments) can do the job pretty quickly and pretty well. In my opinion, using a regular expression in this case is an overkill.
<?php
$str = '<20180203002650.1.EEE3119CC37C5A82#domain.com>';
$str_trimmed = trim($str, '<>');
echo $str_trimmed; // 20180203002650.1.EEE3119CC37C5A82#domain.com
?>
You can see a working demo here.
this function should do what you need.
$str = '<20180203002650.1.EEE3119CC37C5A82#domain.com>';
$cleanString = preg_replace_callback(
'/<|>|and/',
function ($matches) {
return "";
},
$str
);
echo $cleanString;
I'm rewriting a PHP plugin, and there are functions called $expode_top[] & $expode_bottom[]. I understand what the normal explode function does, but what are these?
It seems to be impossible to find an answer on Google because it replaces the underscore with a space.
Those are array variables, not functions, they just happen to start with a keyword you are familiar with. Anything beginning with a $ is a variable in PHP.
Using [] will put the assigned variable into the "next" position of the array. For example:
$expode_top = array();
$expode_top[] = "testing";
if ( $expode_top[0] == "testing" ){
echo "it does equal testing";
}
As #gwillie rightly commented, it could also be a variable function - the name of the variable is replaced and then that function is executed. Second example:
$expode_top = "echo";
$expode_top("testing");
Is functionally the same as:
echo("testing");
Those are array variable names, not functions, as indicated by the $ and []. Also, neither exists as a function.
I have a very simple question. But is really making me crazy.
I have a statement say:
example and example with one php variable like $loggedin_user_name
First of all, I want to store the above sentence in MySQL database and then take it back whenever I want to print the above statement. It seems that their is no issue.
But when I tried to print data after extracting from database it is printing the same statement. But i guess, it has to print the logged in user name instead of $loggedin_user_name in the above statement.
So, is it possible to print the variable within the variable? If yes, please suggest a way.
use sprintf()
$str = "example and example with one php variable like %s";
Then load it from database and fill
$out = sprintf($str, $loggedin_user_name);
If it is always the same variable name, I would suggest using
echo str_replace($fromDb, '$variableToReplace', $variableToReplace);
You can use preg_match to find you variable name in string and then replace it with str_replace.
$name = "ABC";
$bla = "$name";
echo $bla; //ABC
Will always be "ABC", because PHP is evaluating your variable when asigning to $bla.
You can use single-quotes to avoid that behaviour (like $bla='$name'; //$name) or you quote the $-sign (like $bla="\$name"; //$name). Then you can store your string like you wanted into your database.
But you can not (only when using eval(), wich you MUST NOT DO in good PHP-Code) build this behaviour, that php has, when printing fulltext.
Like Mentioned in another answer, you should use printf or sprintf and replace the $loggedin_user_name with %s (for "string).
Best would be to concatinate a string:
$exampleWithUsername = 'example' . $loggedin_user_name;
echo $exampleWithUsername;
'example' is a hardcoded string, but you can give it a variable containing string $example, or directly concatinate $username into $example.
You can use eval function, it can be used like your example:
$loggedin_user_name = 'bilal';
$str = "example and example with one php variable like $loggedin_user_name";
eval("\$str = \"$str\";");
echo $str;
Cons:
If your str variable or string/code which you give to eval as a parameter is filled by users, this usage creates a vulnerability.
In case of a fatal error in the evaluated code, the whole script exits.
I need help figuring out the syntax for the eval function - or even if eval is the right approach. I have a column in my mysql database which holds the name of a PHP function I need to run. There are also PHP variables that would like to leave as variable until they are passed to the function. Below is what I have so far:
eval($valRec[$key]($key,$value));
$valRec is the array which contains the results of a mysql SELECT. $key is a variable which references the name of the column that contains the function name.
$key and $value are the PHP variables that I need to pass into the function.
In the end, I want to end up with:
functionName($key,$value);
which PHP should run.
Hopefully I explained it clearly - thank you in advance for any help!
Eval is probably not what you want. Look at call_user_func and call_user_func_array. They let you call a function whose name is in a variable.
call_user_func($valRec[$key], $key, $value);
All you need to do is:
$valRec[$key]($key,$value);
Reference: variable functions.
In php, you could do below;
$func = 'strtolower';
$foo = $func($bar);
So in your case, $valRec[$key]($key,$value); will just work.
Check the demo.
Addtion:
The reason why your eval not work is because eval need to take a string as parameter, not don't forget ; to end the statement, or it will be syntax error.
So you need to do:
eval($valRec[$key].'($key, $value);');
I haven't used PHP recently, but the concept of eval is to evaluate a string.
As such, you need to create the string representing the line of code you want run.
In your case that means:
eval($valRec[$key] . '($key, $value);');
You've said it yourself, you want to end up with functionName($key,$value); so you need to make a string that is that, then pass it to eval.
see this example,
<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>
this is the output
This is a $string with my $name in it.
This is a cup with my coffee in it.
you need to read this, when is eval evil in php?
Just a simple question. I have a contact form stored in a function because it's just easier to call it on the pages I want it to have.
Now to extend usability, I want to search for {contactform} using str_replace.
Example:
function contactform(){
// bunch of inputs
}
$wysiwyg = str_replace('{contactform}', contactform(), $wysiwyg);
So basically, if {contactform} is found. Replace it with the output of contactform.
Now I know that I can run the function before the replace and store its output in a variable, and then replace it with that same variable. But I'm interested to know if there is a better method than the one I have in mind.
Thanks
To answer your question, you could use PCRE and preg_replace_callback and then either modify your contactform() function or create a wrapper that accepts the matches.
I think your idea of running the function once and storing it in a variable makes more sense though.
Your method is fine, I would set it as a $var if you are planning to use the contents of contactform() more than once.
It might pay to use http://php.net/strpos to check if {contact_form} exists before running the str_replace function.
You could try both ways, and if your server support it, benchmark:
<?php echo 'Memory Usage: '. (!function_exists('memory_get_usage') ? '0' : round(memory_get_usage()/1024/1024, 2)) .'MB'; ?>
you may want to have a look at php's call_user_func() more information here http://php.net/call_user_func
$wysiwyg = 'Some string and {contactform}';
$find = '{contactform}';
strpos($wysiwyg, $find) ? call_user_func($find) : '';
Yes, there is: Write one yourself. (Unless there already is one, which is always hard to be sure in PHP; see my next point.)
Ah, there it is: preg_replace_callback(). Of course, it's one of the three regex libraries and as such, does not do simple string manipulation.
Anyway, my point is: Do not follow PHP's [non-]design guidelines. Write your own multibyte-safe string substitution function with a callback, and do not use call_user_func().