简体   繁体   中英

How to use a href while using htmlspecialchars

Let's say if I have this code

$text = "please visit this <a href="http://example.com">site</a>."
$text = htmlspecialchars($text);
echo $text;

so it's output will be please visit this <a href="http://example.com">site</a>. but I want it's output like this
please visit this site . is there is a way to see if it's a href then do somthing? Thanks.

Only escape the URL itself:

$text = 'please visit this <a href="' . htmlspecialchars('http://example.com') . '">site</a>.'

Notice the switching between single and double quotes.

Your string definition is bad (as you can see by the syntax highlighting). You don't actually need to escape anything in this instance since you want functional HTML.

You can use escape characters like so:

$text = "please visit this <a href=\"http://example.com\">site</a>."
                                   ^- escape here      ^- and here

Sometimes you can get away with using a different set of quotes, like:

// use single quote
$text = 'please visit this <a href="http://example.com">site</a>.'

Another possibility is HEREDOC notation: (stackoverflow doesn't recognize the syntax)

$text = <<<DELIM
please visit this <a href="http://example.com">site</a>.
DELIM;

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