tags:

views:

45

answers:

2

Hi,

Need help here. Am not able to replace the '&' with '&' uses Preg_replace in PHP. But, if I do it manually (edited) on the xml file, it works out fine.

Here are the sample:

$XMLCharactersPreg = "/[&<>\"\'()^*@+]/";
$XMLPregReplace = "&amp;";
$d_Description = "50% offer & 20% further reduction for member";

if (preg_match($XMLCharactersPreg, $d_Description)) {
    echo "A match was found.";
    $XMLDealDescription = preg_replace($XMLCharactersPreg , $XMLPregReplace, $d_Description);
    echo "$XMLDealDescription <br / >";

} else {
    echo "A match was not found.";
}

Thanks.

A: 

Why not use htmlspecialchars?

$XMLDealDescription = htmlspecialchars($d_Description, ENT_QUOTES);

The code then becomes:

$d_Description = "50% offer & 20% further reduction for member"; 

$XMLDealDescription =  htmlspecialchars($d_Description, ENT_QUOTES);
echo "$XMLDealDescription <br / >"; 

This code works fine - the output is:

> g:\Program Files\PHP>php Test\test.php.txt
50% offer &amp; 20% further reduction for member <br / >

Any other errors you get (such as XML well-formedness) is likely due to an error somewhere else in your code. (Also, the <br / > tag seems to have a space between the / and the > which isn't needed).

David_001
Hi David_001,Have tried the code that you posted but it didn't work. Am i missing something here?XML Parsing Error: not well-formed
Raind
A: 

Are you perhaps looking at the result in a browser, which would display &amp; as &? So the source contains &amp;, but you only see & in the browser.

Sjoerd
Raind
Your example code works for me, so it is unclear why it is not working for you.
Sjoerd
Raind
Use the "view source" function of your browser to check whether is has been replaced.
Sjoerd