2011-08-30 12 views
6

Mam witrynę, w której użytkownicy mogą wprowadzać komentarze i opisy. Pozwalam im również wprowadzać linki. Używam strip_tags z wyjątkiem dla linków. Dodaję też rel="nofollow" poprzez proste string_replace.Sprawdzanie składni linków wprowadzanych przez użytkownika

Problem polega na tym, że jeśli użytkownicy zostawiają podwójny cudzysłów na końcu otwierającego tagu, to messe up html. Wszelkie sugestie, jak sprawdzić lub naprawić niepoprawną składnię linków?

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

i podczas wyprowadzania

$ comment = stripslashes ($ komentarzu);

echo $ comment;

Problem polega na tym, że użytkownicy dodają <a href="www.blah.com> i zapominają o ostatnim podwójnym cudzysłowie, a to powoduje, że wyświetlany jest komentarz.

+0

można podać przykładowy kod? –

+0

Mam na myśli, kod PHP z str_replace, który robisz dla rel = "nofollow" –

+0

Przepraszam. Mój pierwszy raz na StackOverflow. Że należy to zrobić. – Brian

Odpowiedz

5

Oto co trzeba zrobić:

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"; 

To wyświetli:

<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

Wow. Dziękuję BoZ. To wydaje się być czymś, co byłoby częstym problemem, ale nie byłem w stanie znaleźć niczego na ten temat. Ta poprawka powinna działać poprawnie. Dzięki jeszcze raz. – Brian

+5

Cieszę się, że Ci się podobało. Mam nadzieję, że to najlepsza odpowiedź, jaką możesz znaleźć. –

+0

+1 Miło! o wiele szybciej niż regexp – Tech4Wilco

Powiązane problemy