Php: remove all tags, but “a href” in a text

后端 未结 2 579
無奈伤痛
無奈伤痛 2021-01-26 04:52

Here\'s my problem:

I have a textarea where the user can enter whatever he wants.

When he sends this text (POST method), on the server side I don\'t filter it

相关标签:
2条回答
  • 2021-01-26 05:35

    When outputting surely you'd be better just using strip_tags and setting "a" to be an allowable element?

    I.e.

    $string = strip_tags($string,'<a>');
    

    This would remove the tags instead of converting them to their entities though. It depends if you need it to convert everything apart from <a> tags into entities, or if you just want to remove the code.

    0 讨论(0)
  • 2021-01-26 05:43

    Just add a preg_replace() function to revert the escaped a tags after your htmlentities() function

    $output = textForWeb($output);
    $output = preg_replace('#&lt;a href=&quot;(?=https:\/\/|http:\/\/)(.*?)&quot;&gt;(.*?)&lt;/a&gt;#i', '<a href="$1">$2</a>', $output);
    
    echo $output;
    

    That way you can still escape all other HTML in a safe way (instead of using strip_tags() function.)

    This preg_replace() function searches for a tags linking to pages starting with http:// or https:// and then replaces the escaped special characters with <, > and ", making the link clickable again.

    0 讨论(0)
提交回复
热议问题