簡體   English   中英

htmlspecialchars並使鏈接可點擊

[英]htmlspecialchars and make links clickable

我有一個處理用戶輸入的PHP腳本。 我需要轉義所有特殊字符,而且還使鏈接可單擊(將它們轉換為<a>元素)。 我需要的是:

function specialCharsAndLinks($text) {
    // magic goes here
}
$inp = "http://web.page/index.php?a1=hi&a2=hello\n<script src=\"http://bad-website.com/exploit.js\"></script>";
$out = specialCharsAndLinks($inp);
echo $out;

輸出應為(以HTML格式):

<a href="http://web.page/index.php?a1=hi&a2=hello">http://web.page/index.php?a1=hi&amp;a2=hello</a>
&lt;script src="http://bad-website.com/exploit.js"&gt;&lt;/script&gt;

請注意,鏈接中的與號保留在href屬性中,但會轉換為&amp; 在鏈接的實際內容中。

在瀏覽器中查看時:

http://web.page/index.php?a1=hi&a2=hello <script src =“ http://bad-website.com/exploit.js”> </ script>

嘗試這個:

$urlEscaped = htmlspecialchars("http://web.page/index.php?a1=hi&a2=hello");
$aTag = '<a href="$urlEscaped">Hello</a>';
echo $aTag;

您的例子不工作,因為如果逃逸整個HTML標簽, a標簽永遠不會被瀏覽器處理,而不是它只會顯示為純文本。

如您所見,stackoverflow會轉義整個輸入(問題/答案...),因此我們實際上可以看到代碼,而不是讓瀏覽器對其進行處理。

我最終用以下方法解決了它:

function process_text($text) {
    $text = htmlspecialchars($text);
    $url_regex = "/(?:http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+(?:\/\S*)?/";
    $text = preg_replace_callback($url_regex, function($matches){
        return '<a href="'.htmlspecialchars_decode($matches[0]).'" rel="nofollow">'.$matches[0]."</a>";
    }, $text);
    return $text;
}

第一行對輸入進行html編碼。
第二行定義URL正則表達式。 可以進行改進,但現在可以使用。
第三行使用preg_replace_callback函數,該函數類似於preg_replace ,但是沒有提供替換字符串,而是提供了返回替換字符串的替換函數
第四行是實際功能。 這是很自我記錄的。 htmlspecialchars_decode撤銷的動作htmlspecialchars (因此使該鏈接有效的,如果它包含一個amperstand)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM