Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting ampersands with str_replace

Tags:

php

xhtml

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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
like image 780
jonners99 Avatar asked Sep 03 '26 15:09

jonners99


2 Answers

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

like image 137
genesis Avatar answered Sep 05 '26 06:09

genesis


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

like image 33
Aleks G Avatar answered Sep 05 '26 04:09

Aleks G