开发者

Converting ampersands with str_replace

开发者 https://www.devze.com 2023-03-20 11:59 出处:网络
We have a news site, I am trying to set up an str_replace to convert the occurences where & is pulled from the database into standards friendly & (with the user still seeing &)

We have a news site, I am trying to set up an str_replace to convert the occurences where & is pulled from the database into standards friendly & (with the user still seeing &)

What happens is I get the following examples outputting on the visible site:

Changing World".  The report
Copper & Gold

instead of the expected space or ampersand. The data is being pulled from a mysqldb with text fields. Where am I going wrong?

My code is:

function textfix($text){
    $find = array('&', '<br>');
    $replace = array('&amp;', '<br />');
    $newtext = str_replace($find, $replace, $text);
    return $newtext;
}

the html stuff is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" lang="en-gb" dir="ltr">开发者_如何学C;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />


this has nothing to do with &nbsp; however if you have &nbsp; in your $text it will be changed to &amp;nbsp;

also tell us what do you see in source-code of that html snippet


I strongly suggest that you use htmlentities() or htmlspecialchars() functions instead of trying to convert the ampersands.


using str_replace() will tell your program to mercilessly covert any & to &amp; even in places where you need it, like with &nbsp; or whatever.

I'd suggest using preg_replace() and using regular expressions such as /&[^\w]/ to make sure you're only replacing independent ampersands.

using preg_replace() you can use the arrays as normal, and the parameters are the same as with str_replace(), but you should use regular expressions as the string values of the find array.

See the PHP manual for more details.

0

精彩评论

暂无评论...
验证码 换一张
取 消