[SOLVED] htmlspecialchars question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

[SOLVED] htmlspecialchars question

Post by neophyte »

I'm pulling text from a database. The text has some html in it. I need to translate special characters like "&" and "<" that might be in the text while allowing things like <b> and <a href> in the body copy. Originally I had coded it like this:

Code: Select all

<?php
 print htmlspecialchars(nl2br($text));
?>
This doesn't work I get <b> <a href> printed to the screen. Is there a way to do this with out doing some sort of REGEX function to replace special chars?

Thanks
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

str_replace('&lt;b&gt;','&lt;b&gt;',$text);
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

okay

Post by neophyte »

Thanks for the tip Feyd, I worked it out like this...

Code: Select all

<?php $specialchars = array("&" => "&", """ => """);
foreach ($specialchars as $key => $val){
 str_replace($key, $val, $text);
 }

print nl2br($text);
>?
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Won't replacing quotes cause some issues with quotes around HTML attributes?

Mac
Post Reply