简体   繁体   中英

Use double and single quotes in an echo statement

I am struggling to work out how I can use both double and single quotes in an echo statement without breaking open the echo.

For example, I want to create a link that outputs like this:

<a href="http:/www.blah.com" class="read-more" onClick="_gaq.push(['_trackEvent', 'External Link', 'Buy Link', 'Item name']);">Read this post...</a>

However I want to output PHP variables in place of the href and as one of the parameters in the onClick

The href part is easy, I can break open the PHP echo and concat the variable in:

echo '<a href="'.$link.'" class="read-more">Read this post...</a>';

But i'm stuck when it comes to the parameters inside the onClick, because I can't include them as the use of ' breaks open my echo:

echo '<a href="<?php echo the_permalink(); ?>" class="read-more" onClick="_gaq.push(['_trackEvent', 'External Link', 'Buy Link', ''. echo $pattern_name .'']);">Read this post...</a>';

So this code above breaks when it gets to the 'trackEvent' part because the single quotes break it open.

What can I do?

反斜杠( 转义字符 )是您最好的朋友:

echo '<a href="'.the_permalink().'" class="read-more" onClick="_gaq.push([\'_trackEvent\', \'External Link\', \'Buy Link\', \''. $pattern_name .'\']);">Read this post...</a>';

You have a few options, but personally i find it ugly code when using something like echo '

I would suggest something more along these lines (escaping)

$pattern_name = "something";
$linkhref = someFunction();
echo "<a href='{$linkhref}' class='read-more' onclick='_gaq.push([\"_trackEvent\", \"External Link\", \"Buy Link\", \"{$pattern_name}\"]);'>Read this post...</a>";

Of this

$pattern_name = "something";
echo "<a href='".someFunction()."' class='read-more' onclick='_gaq.push([\"_trackEvent\", \"External Link\", \"Buy Link\", \"{$pattern_name}\"]);'>Read this post...</a>";

Just a personal preference

Results in...

<a href='index.php' class='read-more' onclick='_gaq.push(["_trackEvent", "External Link", "Buy Link", "something"]);'>Read this post...</a>

Using complex (curly) syntax, http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex

Aside: your HTML code will be rather more readable if you do this:

<a
    href="http:/www.blah.com"
    class="read-more"
    onClick="_gaq.push(['_trackEvent', 'External Link', 'Buy Link', 'Item name']);"
>Read this post...</a>

Each attribute gets its own line, and thus is easy to find, and horizontal scrolling in your editor becomes much less necessary. The great thing is that this is perfectly valid HTML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM