How can I manually interpolate a string? [duplicate] - php

This question already has answers here:
How can I replace a variable in a string with the value in PHP?
(13 answers)
Closed 8 years ago.
The only way I've found to interpolate a string (that is, expand the variables inside it) is the following:
$str = 'This is a $a';
$a = 'test';
echo eval('return "' . $str . '";');
Keep in mind that in a real-life scenario, the strings are created in different places, so I can't just replace 's with "s.
Is there a better way for expanding a single-quoted string without the use of eval()? I'm looking for something that PHP itself provides.
Please note: Using strtr() is just like using something like sprintf(). My question is different than the question linked to in the possible duplicate section of this question, since I am letting the string control how (that is, through what function calls or property accessors) it wants to obtain the content.

There are more mechanisms than PHP string literal syntax to replace placeholders in strings! A pretty common one is sprintf:
$str = 'This is a %s';
$a = 'test';
echo sprintf($str, $a);
http://php.net/sprintf
There are a ton of other more or less specialised templating languages. Pick the one you like best.

Have you heard of strtr()?
It serves this very purpose and is very useful to create dynamic HTML content containing information from a database, for example.
Given the following string:
$str = 'here is some text to greet user {zUserName}';
then you can parse it using strtr():
$userName = 'Mike';
$parsed = strtr($str,array('{zUserName}'=>$userName));
echo $parsed; // outputs: 'here is some text to greet user Mike'
While sprintf is faster in some regards, strtr allows you to control what goes where in a more friendly way (sprintf is not really manageable on very long strings containing, say, a hundred placeholders to be replaced).

Here is a possible solution. I am not sure in your particular scenario if this would work for you, but it would definitely cut out the need for so many single and double quotes.
<?php
class a {
function b() {
return "World";
}
}
$c = new a;
echo eval('Hello {$c->b()}.');
?>

Related

General php format

So, I am just familiarizing myself with php and I see that there are few alternative formats when it comes to writing in php.
What I am confused about is the "dots" or their placements as well other stuffs such as "_".
For example,
<?php
if(!empty($my_post))
{
echo $my_post . ' ' . __('my_post','my_site') . ' + ';
}
?>
It might be a really silly question but could someone explain to me what the function of "dots" in between and just the format itself.
Thanks!
TheSaurus has answered it right. Dots(.) in PHP are the concatenation operators like that plus(+) in java. Whenever you want to build a string with some sub strings, you may use it. There are several other plenty of uses of this, depending on the use.Like One explained in above example.
e.g.:
$line="STACK OVERFLOW";
echo "$line<br/>"
// Some Computation
$line.="is good"; // Here used to concatenate
echo $line
This will output
STACK OVERFLOW
STACK OVERFLOW is good
The dot is the concatenation operator ('.'), which returns the concatenation of its right and left arguments.
<?php
$var = "hello";
$world = "world";
echo "$var" . '$world'; //outputs hello$world
echo "$var" . "$world"; //outputs helloworld
echo "$var" . $world; //outputs helloworld
?>
Read More
The dot
As many have answered before, the dot concatenates strings into a single string. But it's not necessary for bot to be strings. You can concatenate an integer with a string just fine.
<?php
$a = 'Number';
$b = 2;
$c = 'Yay!';
echo $a . $b . $c; // Output: Number2Yay!
?>
The double underscore
In your case, the __() function is just an alias for gettext(): documentation: LINK
Usually, though, the double underscore is used for Magic Methods.
You'll find this piece of text in the documentation:
PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.
You can read all about them here: Magic Methods
P.S. You'll probably find THIS LINK very useful for future reference. I really recommend looking through this list :)
Dots are string concatenation operators in PHP.
So, if I write
$a="3";
$b="text";
echo $a.$b;
The result will be 3text.
If you want to add some space between those;
echo $a.' '.$b;
The result will be 3 text.
Please note that ' ' means space character in string form.
Also, please check other questions before submitting one.

Is it possible to print php variable withing a variable?

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.

Return string/int from evaluated php code?

This is annoying me. In theory it should be easy but I don't live in theory.
Basically, I have an option to set a custom algorithm to make a 'code' that is either string or int.
This is user generated, and I then call that.
I have attempted to execute it using this code:
$code = eval('return($custalg);');
but that returns the actual algorithm entered, and not the value it would produce.
So my question is, how would I manage to execute the string in $custalg as php and then save the result into a variable?
It looks you are not aware of difference between single quoted ' and double quoted " strings in PHP. You should use:
$code = eval("return($custalg);");
if you want $custalog to be expanded:
The most important feature of double-quoted strings is the fact that
variable names will be expanded. See string parsing for details.
See more in docs.
So basically correct syntax depends on what $custalg is and where it is assigned. In your case I guess your $custalg is assigned in main code so you do not want substitution. Use code like this then:
$code = eval("return \$custalg;");
You can get an echoed output with using the PHP output control functions:
ob_start();
eval("echo $custalg;");
$tmp = ob_get_contents();
ob_end_clean();
$evalOutput = $tmp;
Or you just assign the return value to a global variable.

why do php variables need to be identified by $? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why does PHP have a $ sign in front of variables?
In languages like bash and Perl, strings need not be quoted and that is why variable access needs to be identified by using $. Why does PHP need the similar mechanism?
It's a historical decision, probably because it allows to include variables in a string literal:
$variable = "handle to data storage";
echo "a $variable";
Because PHP is influenced by Perl. Back then, when it was conceived, PHP was just a set of Perl scripts.
PHP Constants are a seperate type, but behave much like variables (except they can't be changed, of course... that's what they're constants for) and look a lot like 'em too. For readability, it's nicer to have an identifier. (<- random guess, not)
Besides:
$lol = abcdef;
$lol === 'abcdef'; // true
Undefined constants will throw a notice and will be interpreted as a string.
ohyes, and inside strings, variables can also be used, so an identifier is absolutely necessary (thanks to phihag)
I think simply because without it mixing variable inside string will not be possible
$name = "bond";
echo "My name is $name" ;
Now without $ name will act as string .

Concatenation Operator

This might be a silly question but it struck me, and here i ask.
<?php
$x="Hi";
$y=" There";
$z = $x.$y;
$a = "$x$y";
echo "$z"."<br />"."$a";
?>
$z uses the traditional concatenation operator provided by php and concatenates, conversely $a doesn't,
My questions:
by not using the concatenation operator, does it effect the performance?
If it doesn't why at all have the concatenation operator.
Why have 2 modes of implementation when one does the work?
Only slightly, since PHP has to parse the entire string looking for variables, while with concatenation, it just slaps the two variables together. So there's a tiny performance hit, but it's not noticeable for most things.
It's a lot easier to concatenate variables like $_SERVER['DOCUMENT_ROOT'] using the concatenation operator (with quotes, you have to surround the variable in brackets or remove the single quotes in the array index; plus it just makes the string look all ugly). Plus, the concatenation operator allows more flexibility for formatting. For example, you can break up a long string literal onto multiple lines and then concatenate the different parts of it:
$blah = "This is a really really long string. I don't even know how " .
"long it is, but it's really long. Like, longer than an eel " .
"or even a boa constrictor. Wow.";
You can also use the concatenation operator to directly include return values from functions in a string literal (you can't include a function call in a double-quoted string), like this:
$blah = "This has a " . fn_call() . " result, which can't go in the quotes.";
I'm not sure I entirely understand what you're asking here, but I can say that PHP borrows a lot of things from Perl, and one of Perl's mantras is "There's more than one way to do it."
a. Yes. PHP has to parse the string for variables.
b. Because of lines like: echo 'Your Ip address is' . get_ip() . '.';
For reasons A and B.
In some cases your write less with:
$someLongVarName ="Hi";
$someLongVarName .=" there";
VS
$someLongVarName ="Hi";
$someLongVarName = "$someLongVarName there";
Addressing your last question:
Every language has multiple was of doing the same thing. Flexibility is important in every language since any given method may be better the another from situation to situation. The only thing that you should worry about in regards to this is to be consistent in your own code.

Categories