AFB
AFB

Reputation: 560

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.

Upvotes: 0

Views: 1795

Answers (2)

ponysmith
ponysmith

Reputation: 427

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.

Upvotes: 3

Halcyon
Halcyon

Reputation: 57719

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;

Upvotes: 2

Related Questions