Giuseppe Gambino
Giuseppe Gambino

Reputation: 9

str_replace() failing to match different kinds of hyphens

I'm writing this code:

$response = "PARCHEGGIO BASILE (Cap.) – Via E. Basile – Cavalcavia Brasa - V.le Regione Siciliana - V. Villagrazia (Barone Scala) – V. Emily Balch - V. Villagrazia - V. dell’Usignolo - V. dell’Allodola - V.le Regione Siciliana - VIA DEL LEVRIERE (Bonagia) (capolinea di transito) - V.dell’ Antilope - V. dell’ Ermellino - V.le Regione Siciliana - V. dell’Allodola - V. dell’Usignolo - V. Villagrazia - V.le Regione Siciliana – svincolo Brasa - Via E. Basile - PARCHEGGIO BASILE (Cap.)";
$response =  str_replace( " – " , "@" , $response );
echo $response;

But the result is:

PARCHEGGIO BASILE (Cap.)@Via E. Basile@Cavalcavia Brasa - V.le Regione Siciliana - V. Villagrazia (Barone Scala)@V. Emily Balch - V. Villagrazia - V. dell’Usignolo - V. dell’Allodola - V.le Regione Siciliana - VIA DEL LEVRIERE (Bonagia) (capolinea di transito) - V.dell’ Antilope - V. dell’ Ermellino - V.le Regione Siciliana - V. dell’Allodola - V. dell’Usignolo - V. Villagrazia - V.le Regione Siciliana@svincolo Brasa - Via E. Basile - PARCHEGGIO BASILE (Cap.)

The str_replace() call doesn't function as expected. Where am I going wrong?

Upvotes: 0

Views: 162

Answers (2)

user3377716
user3377716

Reputation:

Your sting was ill formatted, use this str_replace instead

$response = str_replace([' – ', ' - '], "@", $response);

Because the previous string included the 0x2d or as well as 0xe28093 or -, different unicode characters.

Upvotes: 0

zerkms
zerkms

Reputation: 254886

They are different characters, that have 0x2d and 0xe28093 (encoded as UTF-8) codes accordingly.

If you look carefully you can even see that they are of different length.

So, php just does what you instructed it to: it tries to replace a substring, and as soon as there is no entry in the source string - it lefts it untouched.

To replace all - you just use - character in your str_replace call instead of

Useful links:

Upvotes: 2

Related Questions