PHP ternary operators error when concatenating string [duplicate] - php

This question already has answers here:
What is the difference between single-quoted and double-quoted strings in PHP?
(7 answers)
Closed 3 years ago.
I'm essentially converting this php code into a string assigned to a var so I can return it's value within a function:
<?php if ($add_cta=='yes' ){?>
<a class="button" href="<?php echo strip_tags(trim($a_href)); ?>">
<?php echo strip_tags(trim($a_title)); ?>
</a>
<?php } ?>
I have converted the above into the following:
$html = '
($add_cta == "Yes" ? .
' < a class = "button" href = "'.strip_tags(trim($a_href)).
'" > '.strip_tags(trim($a_title)).
' < /a>'. : "")
';
return $html;
But getting unexpected '.' errors on the line ($add_cta == "Yes" ? .'
But that is required to concat the string and php, right? where am I going wrong

You have to correct the usage of your single quotes. Especially the first and the last single quotes are not necessary. PHP does not execute any code inside the single quotes. You can use double quotes, but this will only print variables and makes things more complicated in combination with HTML. The following code uses the correct single quotes:
$html = ($add_cta == "Yes" ? .
'<a class="button" href="'.strip_tags(trim($a_href)).'">'.
strip_tags(trim($a_title)).
'</a>'. : '');
return $html;
Or just use an if statement:
$html = '';
if ($add_cta == "Yes")
{
$href = strip_tags(trim($a_href));
$title = strip_tags(trim($a_title));
$html .= ' <a class="button" href="'.$href.'">'.$title.'</a>';
}
return $html;

try this. You have done some concatenation mistakes which I have fixed
$a_href = "stackoverflow.com";
$a_title = 'Anything';
$html =
($add_cta == "Yes" ?
' < a class = "button" href = "'.strip_tags(trim($a_href)) .
'" > '.strip_tags(trim($a_title)) .
' < /a>' : "")
;
echo $html;

I think the most simple/readable way to do this is by using a separate template which returns the rendered link.
link-template.php
<?php
return '' . strip_tags(trim($a_title)) . '';
The method/function you want to use this template on:
return $add_cta === 'Yes' ? include 'link-template.php' : '';
What you should consider would be to define $a_href and $a_title before including the template

Related

How do you string a variable together along with a string in PHP?

So I have a variable in PHP that I would like to print along with an html tag but I am very new to PHP and I can't seem to get the syntax right
My goal is to output/print the following
<div class="post-block" style="background-image:url(Whatever image here);">
My code is below:
$feature_posts = the_sub_field('feature_image_post');
if ( get_sub_field('post-feature') == "" ) {
echo '<div class="post-block" style="background-image:url(' .$feature_posts");>';
echo '</div>';
}
You are missing the concatenation operator and the closing single quote after your variable:
$feature_posts = the_sub_field('feature_image_post');
if ( get_sub_field('post-feature') == "" ) {
echo '<div class="post-block" style="background-image:url(' . $feature_posts . ')">';
echo '</div>';
}
To keep the format more readable you can use double quotes to allow variables in your string. Just have to remember escaping the quotes within the markup:
$feature_posts = the_sub_field('feature_image_post');
if ( get_sub_field('post-feature') == "" ) {
echo "<div class=\"post-block\" style=\"background-image:url($feature_posts)\">";
echo '</div>';
}
You can make that.
<?php for($i = 0; $i <= 100; $i++){ ?>
<div class="post-block" style="background-image:url(<?php echo the_sub_field('feature_image_post') ?>);"></div>
<?php } ?>
This a sample how you can do.

Avoiding line breaks in HTML output of PHP

Here I have my print function:
<?php
// little helper function to print the results
function printTag($tags) {
foreach($tags as $t) {
echo '<span class="' . $t['tag'] . '">';
echo $t['token'] . "/" . $t['tag'];
echo '</span>';
echo " ";
}
}
$tagger = new PosTagger('lexicon.txt');
?>
And here is what I'm outputting from an HTML form:
<?php
if($_POST['submitbutton'] == "Submit") {
//Check whether the form has been submitted
$tags = $tagger->tag($_POST['texttotag']);
printTag($tags);
}
?>
My problem is, the output in the browser results in strange line breaks in the middle of some of my <span> like so:
<span class="VB">Enter/VB</span> <span class="PRP$">your/PRP$</span> <span class="NN
">text/NN
</span> <span class="TO">to/TO</span> <span class="NN">tag/NN</span> <span class="RB
">here/RB
</span>
This means my CSS definitions don't apply to the "interrupted" spans. Any idea why this is happening and how I can stop it? I've had a good look around and haven't been able to find cause/solution. Thanks.
It seems that your $t['tag'] variable includes a line-break.
You can get rid of that using trim($t['tag']) instead.
It appears that the $t['tag'] in printTag function contains line break character. You can use str_replace function to remove these characters like:
function printTag($tags) {
foreach($tags as $t) {
echo '<span class="' . $t['tag'] . '">';
$ttag = str_replace('\n','',$t['tag']);
$ttag = str_replace('\r','',$ttag);
echo $t['token'] . "/" . $ttag;
echo '</span>';
echo " ";
}
}

CSS style if/else statement not responding

I am trying to have set the position of my li element according to the value of the variable that I will be displaying. For some reason this doesn't seem to be working. Does anyone see anything wrong with my code? Thanks
echo "<li class=\"compensation_post posts_values\" if($compensation == \"Free\") {style=\"left: 540px;\"}>$compensation</li>";
PHP can parse variables in a double-quoted string, but not conditions. So you're going to need to break this out in one of two ways:
Separated:
$style = '';
if ($compensation == "Free")
$style = " style=\"left:540px;\"";
echo "<li class=\"compensation_post posts_values\"$style>$compensation</li>";
Or in-line:
echo "<li class=\"compensation_post posts_values\" "
. ($compensation == "Free" ? "style=\"left:540px;" : "")
. ">$compensation</li>";
I suppose you can also go in and out of php code like:
?><li class=\"compensation_post posts_values\" <?= ($compensation == "Free" ? "style=\"left:540px;\"" : ""); ?>>$compensation</li>
You cannot use an if statement like that. Instead, you could use a shorthand if. Something like this should work:
echo "<li class=\"compensation_post posts_values\"" . (($compensation == 'Free') ? 'style=\"left: 540px;\" : '') . ">$compensation</li>";
Or, you could do like this:
if ($compensation == 'Free')
$style = 'style="left: 540px;"';
echo "<li class=\"compensation_post posts_values\" $style>$compensation</li>";

What is wrong with this PHP code - Unexpected T_CONSTANT

I keep getting the following error in my log
PHP Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ',' or ';'
The error is related to this line but I'm not sure what's wrong with it
<?php
if ($num != null) {
$query_string = 'msisdn=' . $num . '&ref=' . get_post_meta($post->ID, "ref", $single = true) ;
echo '<div class="highlight"><b>Join Now</b></div>';
}
else{
echo '<div class="highlight"><b>Join Now</b></div>';
}
?>
Your adding PHP opening tags when you are already within a PHP tag. You should change to:
<?php
if ($num != null) {
$query_string = 'msisdn='.$num.'&ref='.get_post_meta($post->ID, "ref", $single = true);
echo '<div class="highlight"><b>Join Now</b></div>';
} else {
echo '<div class="highlight"><b>Join Now</b></div>';
}
?>
else{echo '<div class="highlight"><b>Join Now</b></div>';}
There lays the problem. You see the '+2711111111'. it uses " ' ". You'll have to escape that one, because it will end your string there.
Also, you do not need the opening tags for php in their... just remove them as you are already in a php-snippet.
Try this:
<?php
if ($num != null) {
$query_string = 'msisdn=' . $num . '&ref=' . get_post_meta($post->ID, "ref", $single = true);
echo '<div class="highlight"><b>Join Now</b></div>';
} else {
echo '<div class="highlight"><b>Join Now</b></div>';
}
?>
Your problem was that you had a <?php echo... ?> in the middle of a string that was already being echoed. This had a ' in it, which was the type of quote used to encapsulate the string that was already being echoed. You could escape it (like \') but this would have your resulted in <?php echo... ?> being echoed into your HTML, which I doubt is what you want, instead your should remove this and put the function call into the middle of your echo.
This should be easy spot if you are using an editor/IDE with syntax highlighting. If your are not, look at EditPad, Notepad++ (editors) or Eclipse (IDE). Or Google it...
You are trying to echo a string containing <?php ?> tags
echo '<div class="highlight"><b>Join Now</b></div>';
Should propably be
echo '<div class="highlight"><b>Join Now</b></div>';

quotes in html in php problem

I am trying to generate a specific link and accompanying html depednant on the existance of a file. The code I am using to do so:
if(file_exists('../images/'. $pk . '.jpg'))
{
$imageSrc = "../images/". $pk . ".jpg";
$imagehtml = htmlentities(json_encode("<img src=\"".$imageSrc."\" >"));
$screenshotLink = "<p>View Screenshot";
}
else {
$screenshotLink = '';
}
This results in the following, useless html:
View Screenshot
I don't understand this, because the above is essentialy the same code as:
$html = htmlentities(json_encode($ARTICLE_DESC));
$imagehtml = htmlentities(json_encode("<img src='".$imageSrc."' >"));
echo "<a href='#' onclick=\"makewindows(" . $imagehtml . "); return false;\">
<img src='".$imageSrc."' width='".$imageSize["width"]."' height='".$imageSize["height"]."'></a>
<p>Click for full description </p>";
which produces the following html which works fine:
<a href="#" onclick='makewindows("<img src=\"..\/images\/160329461329.jpg\" >"); return false;'>
<img src="../images/160329461329.jpg" width="199" height="300"></a>
I know it has something to do with quotes, but I am not sure what exactly.
Try this:
$imagehtml = htmlspecialchars(json_encode("<img src=\"".$imageSrc."\" >"), ENT_QUOTES);
$screenshotLink = "<p>View Screenshot";
$imagehtml = htmlspecialchars(json_encode('<img src="'.$imageSrc.'" >'), ENT_QUOTES);
$screenshotLink = '<p>View Screenshot';
Why not use ticks?
Lookup the ENT_NOQUOTES parameter in the php manual
And htmlspecialchars() != htmlentities() btw.

Categories