Strict string behavior with the character '¡'

Please look at this:

$str = '¡hola!'; // '¡' is the spanish opening exclamation mark echo $str{0}; // prints nothing echo $str{1}; // prints   echo $str{2}; // prints h 

The PHP script has UTF-8 encoding, and I get the same results as the apache or CLI module. PHP Version: 5.4.6

Why am I getting these strange results?

+4
source share
2 answers

This is because ¡is actually a multibyte character in UTF that PHP does not handle properly through array access ( [0] ). Instead, you'll want to explore multibyte functions: http://php.net/manual/en/book.mbstring.php

This should work as you expect:

 $str = '¡hola!'; echo mb_substr($str, 0, 1, 'UTF-8'); // prints ¡ echo mb_substr($str, 1, 1, 'UTF-8'); // prints h echo mb_substr($str, 2, 1, 'UTF-8'); // prints o 
+2
source

Indexing a string using [] or {} not multibyte.

Use multibyte functions instead, like mb_substr

+4
source

All Articles