php code inside variable with html code - php

I want to add code php to variable with html, for example
$html = '<b></b> <?php echo $lang["text"] ?>';
but it don't interpret php code. What am I doing wrong?

Use string concatenations like this:
$html = '<b></b>' . $lang['text'];
or insert variable in double quoted string like this:
$html = "<b></b>${lang['text']}";
both versions are correct, use the one that you like.

What you want is called string interpolation (read about how it works for PHP).
Your particular example would be solved using
$html = "<b></b> {$lang['text']}";
String interpolation only happens in double quoted string ("string here").

its very important to escape the output. (security basics)
$html = sprintf('<b>%s</b>', htmlspecialchars($lang['text']));

You can't switch from "Output raw text mode" to "Run PHP code mode" in the middle of a string while you are already in "Run PHP code mode"
$html = "<b></b> ${lang['text']}";
… although why you want an empty bold element is beyond me.

<?php
$html = '<b>'.$lang['text'].'</b>';
?>

make sure file extension is php.
<?php
$html = '<b>' . $lang["text"] . '</b>';
?>

Related

PHP: Complicated String With Single and Double Quotes

I'm trying to pass GET variables inside the URL with a bit of html inside of my PHP but can't figure out the quotes situation. I need to embed two variables inside the URL. I have one in but don't know how to embed the other. Here is the string:
echo "<a href='?id=".($id-1)."' class='button'>PREVIOUS</a>";
and here is what I need to go inside
&City=$City
Thanks for the help
Its pretty simple,
echo "<a href='?id=".($id-1)."&city=" . $City . "' class='button'>PREVIOUS</a>";
In php double quotes "" can eval variables inside them.
$test = "123;"
echo "0$test456"; // prints 0123456
In your case you better use single quote ''.
echo '<a href=\'?id=' . ($id-1) . '&City=' . $City . '\' class=\'button\'>PREVIOUS</a>';
or better
echo 'PREVIOUS';
Use something like this:
echo "<a href='?id=".$id."&City=".$city."'>";
You do need (well, it's good practice anyway) to use & for your ampersand. Otherwise it's fairly straight forward;
echo "<a href='?id=".($id-1)."&City=$City' class='button'>PREVIOUS</a>";
This is because you are using double quotes, which means you can put variables directly into the string (there are some exceptions which you might need to put in curly brackets {}).
I suggest you get a text editor with syntax highlighting, such as jEdit (other editors are available).
Hope this helps.
Maybe is it better to use the sprintf function
$id = 100;
$previousId = $id - 1;
$City = 'Amsterdam';
$link = 'PREVIOUS';
echo sprintf($link, $id, $City);

How do I print a character variable within quotes using php function

I need to get this output.
the result is"random"safdsaf
I am using this piece of code
<?php
$x = "random";
echo 'the result is' .$x. 'safdsaf';
?>
But i am getting this
the result israndomsafdsaf
I have to define random before printing it.
i.e. I do not want to change this piece of code
<?php
$x = "random";
What change should i make inside echo to get the desired output?
If you are using the same type of quotes delimit the quotes in your string like this:
echo "The result is\"" .$x. "\"safdsaf";
or simply use two sets of different quotes:
echo 'the result is"' .$x. '"safdsaf';
Output of either line of code:
The result is"random"safdsaf
Try this
Added the little bit space befor ' and added ", it will give the some out put as you want
echo 'the result is "' .$x. '" safdsaf';
the result will be
The result is "random" safdsaf
If you want to print out double quotes you can include them in single quotes
Something like this would do the trick.
$x = '"random"';
If for whatever reason you don't want to use single quotes you can also escape them like :
$x = "\"random\"";
As you want to keep the string, I suggest you change the original line where you put it in :
echo 'the result is"' .$x. '"safdsaf';
the principle stays the same
Here's some reading material : http://php.net/manual/en/language.types.string.php
You can use simply :-
echo 'the result is "' .$x. '" safdsaf';
OR you can use .
echo "the result is \" $x\" safdsaf";
Using the \ before the quote like this: the result is \"random\" safdsaf.
if you have alot of quotes and such in a string, i would suggest using the addslashes(). This method will do the work for you for you.
For more info, take a look here - http://www.w3schools.com/php/func_string_addslashes.asp

Inserting a variable into a string in PHP

I'm putting html variable inside php var but they aren't escaped correctly so I have problem: who can help me? here here it is the code:
$var['foo'] = "<p>$coord->name</p><p>$coord->address</p>Details";
where it's the problem ?
Hmm... several errors in there, but this should work:
<?php
$var['foo'] = "<p>{$coord->name}</p><p>{$coord->address}</p>Details";
$var['foo'] = "<p>".$coord->name."</p><p>".$coord->address."</p>Details";
cheers
For working with such large strings, I favor using sprintf:
$var['foo'] = sprintf(
'<p>%s</p><p>%s</p>Details',
$coord->name,
$coord->address,
site_url($id)
);
Concatenation generally has a small performance advantage over double quotes. Also, in text editors that highlight syntax, the variables stand out better.
$var['foo'] = '<p>' . $coord->name . '</p><p>' . $coord->address . '</p>Details';

PHP read and execute contents of a file as a string

I am trying to read a file as a string and return it to the client to be executed as javascript code in order to save it as a variable. Like so
<?php
$fileName = 'target.js';
$codeAsString = file_get_contents($fileName);
$script = 'var code=\'' . $codeAsString . '\'';
echo $script;
?>
Once returned, I want the variable code to have a string representation of the contents of target.js. However, it isn't working. I suspect it has to do with new line characters and single/double quotes... In Python they have a multi line quote
"""This
is
a "multi"
line
'quote'
"""
Is there anything like this in Javascript/php? I can't even wrap my head around whether I need the single quotes around $codeAsString when appending it to $script. Do I have to manually go in and prepend backslashes before all quotes, double quotes, back slashes...Surely they have helper functions for this
thanks.
json_encode is your friend...
<?php
$fileName = 'target.js';
$codeAsString = file_get_contents($fileName);
$script = 'var code= '.json_encode($codeAsString) .';';
echo $script;
?>
Use PHP function json_encode.

identify and execute php code on a string

I would like to know if it's possible to execute the php code in a string. I mean if I have:
$string = If i say <?php echo 'lala';?> I wanna get "<?php echo 'dada'; ?>";
Does anybody knows how?
[EDIT] It looks like nobody understood. I wanna save a string like
$string = If i say <?php count(array('lala'));?>
in a database and then render it. I can do it using
function render_php($string){
ob_start();
eval('?>' . $string);
$string = ob_get_contents();
ob_end_clean();
return $string;
}
The problem is that I does not reconize php code into "" (quotes) like
I say "<?php echo 'dada'; ?>"
$string = ($test === TRUE) ? 'lala' : 'falala';
There are lots of ways to do what it looks like you're trying to do (if I'm reading what you wrote correctly). The above is a ternary. If the condition evaluates to true then $string will be set to 'lala' else set to 'falala'.
If you're literally asking what you wrote, then use the eval() function. It takes a passed string and executes it as if it were php code. Don't include the <?php ?> tags.
function dropAllTables() {
// drop all tables in db
}
$string = 'dropAllTables();';
eval($string); // will execute the dropAllTables() function
[edit]
You can use the following regular expression to find all the php code:
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
$php_code will be an array where $php_code[0] will return an array of all the matches with the code + <?php ?> tags. $php_code[2] will be an array with just the code to execute.
So,
$string = "array has <?php count(array('lala')); ?> 1 member <?php count(array('falala')); ?>";
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
echo $php_code[0][0][0]; // <?php count(array('lala')); ?>
echo $php_code[2][0][0]; // count(array('lala'));
This should be helpful for what you want to do.
Looks like you are trying to concatenate. Use the concatenation operator "."
$string = "if i say " . $lala . " I wanna get " . $dada;
or
$string = "if i say {$lala} I wanna get {$dada}.";
That is what I get since your string looks to be a php variable.
EDIT:
<?php ?> is used when you want to tell the PHP interpreter that the code in those brackets should be interpreted as PHP. When working within those PHP brackets you do not need to include them again. So as you would just do this:
// You create a string:
$myString = "This is my string.";
// You decide you want to add something to it.
$myString .= getMyNameFunction(); // not $myString .= <?php getMyNameFunction() ?>;
The string is created, then the results of getMyNameFunction() are appended to it. Now if you declared the $myString variable at the top of your page, and wanted to use it later you would do this:
<span id="myString"><?php echo $myString; ?></span>
This would tell the interpreter to add the contents of the $myString variable between the tags.
Use token_get_all() on the string, then look for a T_OPEN_TAG token, start copying from there, look for a T_CLOSE_TAG token and stop there. The string between the token next to T_OPEN_TAG and until the token right before T_CLOSE_TAG is your PHP code.
This is fast and cannot fail, since it uses PHP's tokenizer to parse the string. You will always find the bits of PHP code inside the string, even if the string contains comments or other strings which might contain ?> or any other related substrings that will confuse regular expressions or a hand-written, slow, pure PHP parser.
I would consider not storing your PHP code blocks in a database and evaluating them using eval. There is usually a better solution. Read about Design Pattern, OOP, Polymorphism.
You could use the eval() function.

Categories