PHP allow some HTML tags, write code in screen
I'd like to allow user to add link in text, <b> and <code>
, so I do:
$texto = nl2br($texto);
$texto = strip_tags($texto, "<br><a><b><code>");
This will allow users to enter something like this:
<b>Some</b> text <a href="/someurl">Link</a> and
<code>
<?php
echo ""; ?>
</code>
The link will be a link, the bold text will be bold...
The problem is the <code>
tag. I'd like to allow users to place javascript, html, <?php
but the code cannot run, only to show.
Any ideas how to allow some tags and the other ones I scape?
Thanks!
Answer
Solution:
I think you are looking for htmlentities. This function will escape tags from your code. So they will be printed instead of interpreted.
//edit because I read the comments. I missed that you don't want htmlentities. In that case you could preg_replace "<" ( ">") with "<" (">") in matching tags.
Answer
Solution:
When someone create a post, I will allow links in it to have target _self (default) or _blank.
$texto = htmlentities($texto);
$texto = str_replace('<a href="', '<a href="', $texto);
$texto = str_replace('" target="_blank">', '" target="_blank">', $texto);
$texto = str_replace('" target="_self">', '">', $texto);
$texto = str_replace('</a>', '</a>', $texto);
I used target to know when to close the a href=" ">
self_ will be the default link. The same I will do to b and code.
Source