1

假设我有这个代码

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

所以它的输出会是please visit this <a href="http://example.com">site</a>. ,但我想要这样的输出,
请访问这个站点。有没有办法查看它是否是一个 href 然后做某事?谢谢。

4

2 回答 2

2

仅转义 URL 本身:

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

注意单引号和双引号之间的切换。

于 2013-07-25T16:11:22.450 回答
1

您的字符串定义很糟糕(正如您通过语法突出显示所看到的那样)。在这种情况下,您实际上不需要转义任何内容,因为您需要功能性 HTML。

您可以像这样使用转义字符:

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

有时您可以使用一组不同的引号,例如:

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

另一种可能性是 HEREDOC 表示法:(stackoverflow 无法识别语法)

$text = <<<DELIM
please visit this <a href="http://example.com">site</a>.
DELIM;
于 2013-07-25T15:44:20.433 回答