Question

Often when writing PHP I'll have it output some HTML like this -

echo "<a href="../" title="link title">".$link_text."</a>";

Obviously this won't parse as I need to escape the double quotes in the attributes of the <a> element. Is there a regex that would quickly do this rather than me manually adding the backslashes?

One other thing - the regex shouldn't escape double quotes outside of the tag (e.g. where I've appended the $link_text variable.

Any ideas?

Was it helpful?

Solution

You should just use single-quotes instead:

echo '<a href="../" title="link title">' . $link_text . '</a>';

OTHER TIPS

Solutions I can come up with (not without escaping):

  • Single quotes

    echo '<a href="../">' . $link_text. '</a>';
    
  • Use double quotes

    echo "<a href='../'>$link_text</a>";
    
  • Sprintf

    echo sprintf('<a href="../">%s</a>', $link_text);
    
  • Use HEREDOC

    echo <<<EOF
    <a href="../">$link_text</a>
    EOF;
    
  • Use template engine like smarty

  • Exit PHP-mode:

    ?><a href="../"><?php echo $link_text ?></a><?php // other code...
    

BTW, be sure to use htmlspecialchars() on $link_text variable, or you’ll have a XSS security hole.

Use (This syntax dont worry about quotes etc)

echo <<<EOT
<a href="../" title="link title">$link_text</a>
EOT;

I'd strongly suggest using templating instead of trying to build strings.

In raw PHP:

<a href="../" title="link title"><?php echo $link_text; ?></a>

use single quotes or use heredoc. I'd prefer the last.

I think you can use

http://www.example.com/.../Learning-Tutorials/ACTIVE-USER-ACCOUNT/verify.php?email='.$email.'&hash='.$hash.'

"<a href="//www.example.com/.../Learning-Tutorials/ACTIVE-USER-ACCOUNT/verify.php?email="$email&hash=$hash>Click Here to Active</a>"

try it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top