KANAYO AUGUSTIN UG
KANAYO AUGUSTIN UG

Reputation: 2188

How do I replace some texts in a php string

I want to replace < and > in a php string before inserting into the database so when a user types a code, it won't execute its function so I did this:

$comment = str_replace("<", "&lt;", $comment);
$comment = str_replace(">", "&gt;", $comment);

But I also have something like this within the string <3msg which I don't want to replace Please How do I run my code.

Upvotes: 0

Views: 57

Answers (5)

Archish
Archish

Reputation: 870

See Here.

you can use htmlentities() to achieve your output.

$str = "A 'quote' is <b>and</b>";

// Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str);

// Outputs: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str, ENT_QUOTES);

PS

to see result, see view source you it will look a like this. This

Upvotes: 0

Raghav Patel
Raghav Patel

Reputation: 843

Try this:

Useing php function:

htmlspecialchars($comment);

Upvotes: 0

Daniel Waghorn
Daniel Waghorn

Reputation: 2985

If you want to sanitize database input to remove scripts etc then you can use strip_tags like this:

$comment = strip_tags($comment)

Alternatively if you want to keep tags but not allow code injection then you can also use htmlspecialchars which will make a more thorough and comprehensive conversion to ensure you don't miss anything.

Upvotes: 0

JRsz
JRsz

Reputation: 2941

If you have one character at different places you need to be more specifi, for example chars which are always next to this or something else. Otherwise you are out of luck since you have to exactly identify the char(s) which you want to replace. For the scenario aboce there is a function called htmlspecialchars (Link)

If you want to be sure that nothing interferes with your query and no sql injection attacks can occur I suggest that you used prepared statements as often as you can. You can read mor about this here and if this is not enough I can give you examples for this.

Upvotes: 0

Mani
Mani

Reputation: 2655

Use like this

$comment = str_replace("<", "&#60;", $comment);
$comment = str_replace(">", "&#62;", $comment);
$comment = str_replace("&#60;3msg", "<3msg", $comment);

Upvotes: 1

Related Questions