Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP str_replace doesnt replace character "°"

Hello !

I am getting a String from a .xlsx file ->"N°X"

I would like to replace "N°" by Num_X

I am trying to do this with

$var = str_replace("N°","Num_",$var);

But nothing is replaced (according to echo $var) problem come from ° because when i try to replace some String by other (without °) str_replace works

Any suggestions ?

like image 510
John Snow Avatar asked May 29 '26 16:05

John Snow


1 Answers

Ensure that input string is UTF8.

$var = "N°X";
print mb_detect_encoding($var);

If you don't get UTF-8 out of this, convert it:

$var = mb_convert_encoding($var, 'UTF-8');

And then your str_replace will work as intended.

Another tool that might help you with encoding issues is xxd.

php -r '$var = "N°X"; echo $var;' | xxd

should return

00000000: 4ec2 b058                                N..X

which reveals the middle character is encoded as C2B0 hex, which is Unicode Character 'DEGREE SIGN' (U+00B0). fileformat.info comes handy now.

like image 67
Vojtěch Pithart Avatar answered Jun 01 '26 07:06

Vojtěch Pithart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!