Reputation: 23409
I have a long string with several special characters, specifically quotes (", ') and greater, less than brackets.. (<, >) and it's messing up my HTML.
I was wondering if there was a simple way to replace all occurrences of these with their ascii equivalents (> , < , etc) before I spend a bunch of time writing my own function. I'm terrible at RegEx :/
Thanks for your responses.
Upvotes: 0
Views: 2251
Reputation: 1459
There are htmlentities()
and htmlspecialchars()
available, depending on what you exactly need. If you only want to break ,
, <
and >
, you can do
$new_str = htmlspecialchars($str, ENT_NOQUOTES);
Upvotes: 2
Reputation: 4018
You can use php's str_replace function. Check the php manual at http://php.net/manual/en/function.str-replace.php.
$text = str_replace('<', '', $text);
This code removes the less than sign from $text by replacing it with an empty string.
I would strongly recommend you explore the regex approach using preg_replace(), though. It's faster and much more powerful.
Upvotes: 1
Reputation: 5607
I believe you're looking for htmlspecialchars.
This function will replace all html characters with their html entity equivalents.
Ex:
<?php
$before="<code>";
$after=htmlspecialchars($before);
echo $after; //<code>
?>
Be sure to use ENT_QUOTES as the second argument if you want to also replace single quotes.
Upvotes: 4