Reputation: 61
How can I check if the value of a textarea has HTML in it using PHP?
I have read multiple posts, I tried the following:
if ($text != strip_tags($text))
// text contains html
and tried
if (preg_match("/([\<])([^\>]{1,})*([\>])/i", $string)) {
echo "string contains html";
}
and some other regex. But all give the same result. If I enter only one line (without html) in the textarea and validate it it is fine, it says there is no HTML. If I enter more lines (even without html tags) it says there are html tags but there aren't. Is there a transparent <br>
? Even when I echo/verify the string no html tag is shown.
How come when I have multiple lines in a textarea without html chars it automatically says there are? Are there any other ways of verifying if there are html tags in a textarea?
Thank you!
Upvotes: 1
Views: 1320
Reputation: 41
If you enter more lines in a textarea the "wrapper" will add an (invisible) carriage return, so a invisible html code is added to your text. Try using one of the wrap methods below and see if it works.
<textarea name="userInput" cols="40" rows="6" wrap="virtual"></textarea>
Try to set the wrap method to: virual, hard, soft, physical or off
Upvotes: 0
Reputation: 43
Have you tried something like
if($text!=htmlspecialchars($text))
{ echo 'This contains HTML tags!!'; }
This should not care about the line breaks.
Upvotes: 2
Reputation:
Use something like:
$string_checked = str_replace("<", "#LESSTHAN#", $string);
Not only will it check the code for HTML, it'll convert to another character (or characters) so that the user CAN submit it, but it can be made harmless.
For instance, converting < to #LESSTHAN# will allow you to write it to a database and then retrieve it with no problem...and unless that string is going back into a textarea that is editable, you can choose to leave it as-is. If you want a user to be able to see his original HTML tags he entered, simply convert the string back before placing it in the pre-filled textarea.
$string_checked = str_replace("#LESSTHAN#", "<", $string);
This would even allow you to permit certain HTML tags to be used (like bold, italic, etc.) that can't possibly do any real damage to the way an HTML page works (wouldn't break a form is what I mean).
That's it.
Upvotes: 0