Akos
Akos

Reputation: 41

Strip tags from text?

I have a form. When users submit the data, my script checks the text for php/html with

$text1 = strip_tags($text);

Then it inserts the data into the database. But when users submit something like this: "I totally <3 this website", it only inserts: "I totally". How can I fix this?

(I need to remove the tags)

Upvotes: 1

Views: 402

Answers (5)

knittl
knittl

Reputation: 265171

if you want to put it into your db, don't use strip_tags but the appropriate mysqli_real_escape_string function or prepared statements. later, when outputting the content on an html page, use htmlspecialchars

Upvotes: 0

dakdad
dakdad

Reputation: 2955

While the correct answer would be to use htmlentities as noted in other answers, you can always have an array to pre-process the $text before stripping out tags.

$search = array('<3', ':<');
$replace = array('&lt;3', ':&lt;');

echo strip_tags(str_replace($search, $replace, $text));

Obviously, you'd have to update your array every time you get a new instance of these special cases - so, probably need to think of a proper outcome.

Upvotes: 0

adlawson
adlawson

Reputation: 6431

I'm not sure why you want to do this, but you can strip out < and > by doing

$stripped = str_replace(array('<', '>'), '', $text);

but i would suggest to escape the string instead like this

$escaped = htmlspecialchars($text);
// or
$escaped = htmlentities($text);

Upvotes: 0

RiaD
RiaD

Reputation: 47619

You may replace tags by their eqiualents, don't delete it. Use

htmlspecialchars()

Upvotes: 0

galymzhan
galymzhan

Reputation: 5523

You need to escape those characters instead of stripping them out. You can use the htmlspecialchars function to achieve it. For example:

$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;

It escapes special characters as HTML entities so they will be properly displayed.

Upvotes: 3

Related Questions