2011-08-30 4 views
6

ユーザーがコメントと説明を入力できるサイトがあります。私は彼らも同様にリンクを入力することができます。私はリンクを除いてstrip_tagsを使用します。私はまた、単純なstring_replaceを通じてrel="nofollow"を追加します。ユーザー入力のリンク構文を確認する

問題は、ユーザーが開始タグの最後に二重引用符を残してしまうと、htmlが壊れてしまうことです。間違ったリンク構文をチェックしたり修正したりする方法に関する提案はありますか?

$comment = $_POST['comment'];
$comment = strip_tags($comment,"<a>");
$comment = str_replace('<a','<a rel="nofollow"',$comment);
$comment = mysql_real_escape_string($comment);

$コメント=にstripslashes($コメント)を出力します。

echo $ comment;

ユーザーが<a href="www.blah.com>を追加して最後の二重引用符を忘れると、これはコメントdivの表示方法を失ってしまいます。ここで

+0

あなたは、サンプルコードを与えることができますか? –

+0

私はrel = "nofollow"のためにstr_replaceを使ったPHPコードを意味します –

+0

申し訳ありません。 StackOverflowで初めて。それはそれを行う必要があります。 – Brian

答えて

5

は、あなたがしなければならないものです:

function fixLink($link) { 
    $link = str_replace(array('<a', '"', '</a>'), '', $link); 
    $link = str_replace(
     array('=', '>', ' '), 
     array('="', '">', '" '), 
     $link); 
    return '<a rel="nofollow' . $link . '</a>'; 
}  

echo fixLink('<a href="/index.html>asd</a>') . "\n"; 
echo fixLink('<a class="awesome" href="/index.html>asd</a>') . "\n"; 
echo fixLink('<a href="/index.html class="awesome">asd</a>') . "\n"; 
echo fixLink('<a target="_blank" href="/index.html class="awesome">asd</a>') . "\n"; 
echo fixLink('<a target="_blank" href="/index.html class="awesome>asd</a>') . "\n"; 
echo fixLink('<a target="_blank" href="/index.html target="_blank" class="awesome">asd</a>') . "\n"; 
echo fixLink('<a href="/index.html class=awesome">asd</a>') . "\n"; 

その出力は以下となります。

<a rel="nofollow" href="/index.html">asd</a> 
<a rel="nofollow" class="awesome" href="/index.html">asd</a> 
<a rel="nofollow" href="/index.html" class="awesome">asd</a> 
<a rel="nofollow" target="_blank" href="/index.html" class="awesome">asd</a> 
<a rel="nofollow" target="_blank" href="/index.html" class="awesome">asd</a> 
<a rel="nofollow" target="_blank" href="/index.html" target="_blank" class="awesome">asd</a> 
<a rel="nofollow" href="/index.html" class="awesome">asd</a> 
+0

うわー。ありがとうBoZ。これはよくある問題のようなものですが、何も見つけられませんでした。この修正はうまくいくはずです。再度、感謝します。 – Brian

+5

うれしかったです。私はそれがあなたが見つけることができる最高の答えだと思います。 –

+0

+1ニース!正規表現よりも高速に – Tech4Wilco