Calling PHP function from within a string - php

I can't find a solution how to combine single and double quotes to echo HTML and call a function at the same time:
foreach ($result as $r) {
echo "<a href='get_permalink(get_page($r->id))'>".get_permalink(get_page($r->id)).'</a><br>';
}
Problem is this part is parsed as text, not php
"<a href='get_permalink(get_page($r->id))'>"
Cansome one help me to combine this? get_permalinks and get page are wordpress built in functions, so they should have function behavior

You can't call a function inside double " quotes.
foreach ($result as $r)
{
echo "<a href='".get_permalink(get_page($r->id))."'>".get_permalink(get_page($r->id)).'</a><br>';
}

It's not possible to run PHP code when it's inside a string (unless with eval). However, you can use printf() to separate code from string:
$url = get_permalink(get_page($r->id));
printf('%1$s<br>', htmlspecialchars($url, ENT_QUOTES, 'UTF-8'));
The %1$s is a positional format specifier; this is done so that the encoded $url value only has to be passed once.

Just concat the string like this:
echo "<a href='". get_permalink(get_page($r->id)) . "'>" . get_permalink(get_page($r->id)) . "</a><br>";
Also if you want to know what's the difference between single and double quotes see this:
What is the difference between single-quoted and double-quoted strings in PHP?

try this way:
if($result as $r)
{
echo "<a href='" . get_permalink(get_page($r->id)) . "'>" . get_permalink(get_page($r->id)) . '</a><br>';
}

Related

PHP prevent html entity creation at string concatenation

How can i prevent that PHP converts a recognized part of a string to an html-entity?
So e.g. lets say i have to concat parts together to an url, like:
echo '&' . 'section=' . '<br>';
$a = '&a';
$b = 'mplitude=';
echo "{$a}{$b}" . '<br>';
echo sprintf("%s%s", '&quote', '=');
the code above prints the following:
§ion=
&litude=
"e=
instead of:
&section=
&amplitude=
&quote=
how can this be prevented without throwing filters on it trying to convert the symbols back to an string again?
You need using htmlspecialchars function:
echo htmlspecialchars('&' . 'section=' . '<br>');

How do I escape quotes in URL?

I want to insert a URL all into single quotes. I have tried using both single and double quotes, but it is not working. I checked this question - Escaping single quote in URL link, but it did not help:
<?php
echo '\'' base_url().'\'index.php?admin/product/delete/1\'';
echo '\''; echo base_url().index.php?admin/product/delete/1\'';
echo '\'. base_url().index.php?admin/product/delete/1\'';
echo "\'"; echo base_url().'index.php?admin/product/delete/1\'";
?>
I am trying to achieve this:
'http://localhost/my_site/index.php?admin/product/delete/1'
The URL in single quotes.
If you really want to use only single quotes, try this:
echo '\'' . base_url() . 'index.php?admin/product/delete/1\'';
Just simple:
echo "'" . base_url() . "index.php?admin/product/delete/1'";
You can use double-quotes to pass variables into strings in PHP. On top of enhancing readability, this also saves you the trouble of escaping single quotes.
So for example:
<?php
$foo = 'bar';
echo 'single-quoted string: $foo <br />';
echo "double-quoted string: $foo <br />"; // "$foo" works, "{$foo}" is better
echo "double-quoted string: \$foo <br />"; // Backslash escapes
?>
Prints (emphasis mine):
single-quoted string: $foo
double-quoted string: bar
double-quoted string: $foo
So to update your example:
<?php
/* ... */
$baseurl = base_url();
echo "'{$baseurl}index.php?admin/product/delete/1'";
?>
Or how about we put it all into a variable and gain a little readability:
<?php
/* ... */
$baseurl = base_url();
$fullurl = $baseurl . 'index.php?admin/product/delete/1';
echo "'{$fullurl}'";
?>
echo "'" . base_url() . "index.php?admin/product/delete/1'";

using single and double quotes in php form

I ran into this code:
function input_text($elem, $val) {
print '<input type = "test" name="' . $elem .'" val="';
print htmlentities($val[elem]) . '"/>';
I m confused about the code: name="' . $elem .'" val="';
print htmlentities($val[elem]) . '"/>'
1) why put single quotes and dot inside double quotes around $elem? Can i just use double quotes like name="$elem".
2) what is the meaning of these code: val="';
print htmlentities($val[elem]) . '"/>'
1) Since the string being printed is surrounded with single quotes, variables are not expanded inside it; variables are only expanded inside double-quoted strings. So concatenation is necessary. If you change it to use double quotes, you could do variable interpolation:
print "<input type='test' name='$elem' val='";
2) There's no special meaning to it. The programmer simply chose to split up the commands to print this piece of HTML into two PHP print statements. So first he prints val=", then he prints htmlentities($val[elem]) . "">>'
The function could be rewritten as:
function input_text($elem, $val) {
print "<input type='test' name='$elem' val='" . htmlentities($val[elem]) . "'/>";
}
You have to use concatenation around htmlentities() -- only variables can be interpolated into strings, not function calls. However, you could assign the value to a variable first if you want:
function input_text($elem, $val) {
$valent = htmlentities($val[elem]);
print "<input type='test' name='$elem' val='$valent'/>";
}
BTW, $val[elem] looks like a typo, it probably should be $val[$elem].
The single quotes in this case denote a string in PHP.
$var = 'This is a String';
The reason they are used in conjunction with the double quotes is because the double quotes must be printed to get the correct HTML output of
<input type="test" name="someName" val="someValue" />
The . operator in PHP is the concatenation operator meaning combine 2 strings into 1.
$var = 'This' . ' and that'; //Evaluates to 'This and that'

passing php variable in onClick function

I want to pass the php variable value in onClick function.
When i pass the php variable, in the UI i am getting the variable itself instead I need the value in the variable.
Below is code snippet, please help me.
<?php
print '<td>';
$node = $name->item(0)->nodeValue;
$insert= "cubicle"."$node<br>";
Echo '<a href= "#" onClick= showDetails("$node");>'. $insert .'</a> ';
print '</td>';
?>
Variable parsing is only done in double quoted strings. You can use string concatenation or, what I find more readable, printf [docs]:
printf('%s ', $node, $insert);
The best way would be to not echo HTML at all, but to embed PHP in HTML:
<?php
$node = $name->item(0)->nodeValue;
$insert = "cubicle" . $node;
?>
<td>
<a href= "#" onClick="showDetails('<?php echo $node;?>');">
<?php echo $insert; ?> <br />
</a>
</td>
You have to think less about quotes and debugging your HTML is easier too.
Note: If $node is representing a number, you don't need quotations marks around the argument.
you shouldn't be wrapping $node in '"':
Echo '<a href= "#" onClick= showDetails($node);>'. $insert .'</a> ';
If you want the value of $node to be in a string, thn i would do:
Echo '<a href= "#" onClick= showDetails("' . $node. '");>'. $insert .'</a> ';
$var = "Hello World!";
echo "$var"; // echoes Hello World!
echo '$var'; // echoes $var
Don't mix up " and ', they both have importance. If you use some " in your string and don't want to use the same character as delimiter, use this trick:
echo 'I say "Hello" to ' . $name . '!';
I think you are searching for PHP function json_encode which converts PHP variable into JavaScript object.
It's more secure than passing the value right in the output.
Echo '<a href= "#" onClick= showDetails("'.$node.'");>'. $insert .'</a> ';
I have been using curly braces lately instead of concatenation. I think it looks better/is more readable, and mostly I find it is easier and less prone to human error - keeping all those quotes straight! You will also need quotes around the contents inside of onClick.
Instead of this:
Echo '<a href= "#" onClick= showDetails($node);>'. $insert .'</a> ';
Try this:
Echo '{$insert} ';
As a side note, I usually use double quotes to wrap my echo statement and strictly use single quotes within it. That is just my style though. However you do it, be sure to keep it straight. So my version would look like this:
echo "<a href='#' onClick='showDetails({$node});'>{$insert}</a>";

Quotes problem when passing value to Javascript

I am using like
$myPage .= '<td><a href=\'javascript:editProduct('
.$row['id']
.',"'
.$row['name']
.'")\'>Edit</a></td>';
where $row['name'] has quotes in its value. it breaks. how do i solve the issue both from php side and js side...
$row['name'] is value from DB. and it will have value like pradeep's and pradeep"s also
i used like
$myPage .= '<td><a href=\'javascript:editProduct('.addslashes($row['id']).',"'.addslashes($row['name']).'")\'>Edit</a></td>';
it solves the issue of double quotes. but when i have single quotes in value the javascrit link looks like
javascript:editProduct(28,"pradeep\
it actually breaks..
And how do i strip down the slashes added by addslashes in javascript..
UPDATE - FINAL CODE
$myPage .= '<td><a href=\'javascript:editProduct('.$row['id'].',"'.htmlentities($row['name'],ENT_QUOTES).'")\'>Edit</a></td>';
and js looks like
function editProduct(id,name){
alert(name);
}
can any one solve my issues
Try:
$myPage .= "<td><a href='javascript:editProduct({$row['id']},\""
. htmlentities( $row['name'] )
. "\")'>Edit</a></td>";
htmlentities default behaviour is to convert double quotes and leave single quotes alone, if you require converting single and double quotes, then call it like this:
htmlentities( $row[ 'name' ], ENT_QUOTES )
Also, using { .. } in "..." strings is the correct way to substitute variables.
The PHP string
'<a href=\'javascript:editProduct('.$row['id'].',"'.$row['name'].'")\'>';
outputs (assuming some values)
<td><a href='javascript:editProduct(123,"abc")'></td>
Presumably it breaks if $row['name'] contains a " quote. You could replace such quotes with a \" in the string before you output it using str_replace('"', '\"', $row['name'])

Categories