7

I have a HTML string containing £ signs, for some reason i'm not able to replace them. I'm assuming this is an encoding issue although i can't work out how. The site is using ISO-8859-1 for its encoding

$str = '<span class="price">£89.99</span>';
var_dump(mb_detect_encoding($str, 'ISO-8859-1', true)); // outputs ISO-8859-1

echo str_replace(array("£","&pound;"),"",$str); // nothing is removed

echo htmlentities($str); // the entire string is converted, including £ to &pound;

Any ideas?

EDIT

should have pointed out i want to replace the £ with &pound; - i had temporarily added &pound to the array of items to replace in case it had already been converted

robjmills
  • 18,438
  • 15
  • 77
  • 121

4 Answers4

7

Just a guess but could it be that even thou your website outputs in ISO-8859-1 encoding, your actual *.php files are saved as utf-8? i don't think that str_replace works correctly with utf-8 strings. To test it try:

str_replace(utf8_decode("£"),"&pound;",utf8_decode($str));

Yeah, if this works then your *.php files are saved in utf-8 encoding. This means all the string constants are in utf-8. It's probably worth switching default encoding in your IDE to ISO-8859-1

Ivan
  • 3,567
  • 17
  • 25
  • That is my guess to. Check the encoding of "£". – PiTheNumber Nov 22 '11 at 13:48
  • I must point out i have no idea how and why this works though – robjmills Nov 22 '11 at 13:58
  • @seengee your IDE or text editor saves *.php files in utf-8 encoding. When PHP reads the strings in your source code it reads them in the same utf-8 encoding. PHP5 doesn't have full unicode support so some functionality is flawed. Changing settings in your text-editor/IDE to save your source code in ISO-8859-1 encoding will prevent this problems, and you will not need to use utf8_decode() – Ivan Nov 22 '11 at 14:03
  • @Ivan - i have never even thought of changing that in Netbeans, you're right though. switching to ISO in the Netbeans settings means a standard str_replace works! – robjmills Nov 22 '11 at 14:10
1
html_entity_decode(str_replace("&pound;", "", htmlentities($str)));
Jan Vorcak
  • 19,261
  • 14
  • 54
  • 90
0
$data = str_replace("£","&pound;",utf8_encode($data));
echo $data;
Damien Overeem
  • 4,487
  • 4
  • 36
  • 55
him
  • 3,325
  • 3
  • 14
  • 17
  • 2
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – mx0 Nov 06 '17 at 09:56
0
$str = '<span class="price">£89.99</span>';
echo str_replace("£","&pound;",$str);

Output:

<span class="price">&pound;89.99</span>
Phill Pafford
  • 83,471
  • 91
  • 263
  • 383
  • i know that should work, thats where the question comes from! See my note in Ivan's answer for the solution – robjmills Nov 22 '11 at 13:54