I wrestled a bear once.
I wrestled a bear once.

Reputation: 23409

PHP alternative for preg_replace()?

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 (&gt; , &lt; , 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

Answers (3)

uranusjr
uranusjr

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

Anton
Anton

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

Sean Johnson
Sean Johnson

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; //&lt;code&gt;
?>

Be sure to use ENT_QUOTES as the second argument if you want to also replace single quotes.

Upvotes: 4

Related Questions