è possibile utilizzare la 'u' modificatore con PCRE regex; vedi Pattern Modifiers (citando):
u (PCRE8)
Questo modificatore attiva ulteriori funzionalità di PCRE che sono incompatibili con Perl. Le stringhe modello vengono considerate UTF-8. Questo modificatore è disponibile da PHP 4.1.0 o successivo su Unix e da PHP 4.2.3 su win32. La validità UTF-8 del modello è verificata da PHP 4.3.5.
Per esempio, considerando questo codice:
header('Content-type: text/html; charset=UTF-8'); // So the browser doesn't make our lives harder
$str = "abc 文字化け, efg";
$results = array();
preg_match_all('/./', $str, $results);
var_dump($results[0]);
si otterrà un risultato inutilizzabile:
array
0 => string 'a' (length=1)
1 => string 'b' (length=1)
2 => string 'c' (length=1)
3 => string ' ' (length=1)
4 => string '�' (length=1)
5 => string '�' (length=1)
6 => string '�' (length=1)
7 => string '�' (length=1)
8 => string '�' (length=1)
9 => string '�' (length=1)
10 => string '�' (length=1)
11 => string '�' (length=1)
12 => string '�' (length=1)
13 => string '�' (length=1)
14 => string '�' (length=1)
15 => string '�' (length=1)
16 => string ',' (length=1)
17 => string ' ' (length=1)
18 => string 'e' (length=1)
19 => string 'f' (length=1)
20 => string 'g' (length=1)
Ma, con questo codice:
header('Content-type: text/html; charset=UTF-8'); // So the browser doesn't make our lives harder
$str = "abc 文字化け, efg";
$results = array();
preg_match_all('/./u', $str, $results);
var_dump($results[0]);
(Si noti la 'u' alla fine della regex)
si ottiene ciò che si vuole:
array
0 => string 'a' (length=1)
1 => string 'b' (length=1)
2 => string 'c' (length=1)
3 => string ' ' (length=1)
4 => string '文' (length=3)
5 => string '字' (length=3)
6 => string '化' (length=3)
7 => string 'け' (length=3)
8 => string ',' (length=1)
9 => string ' ' (length=1)
10 => string 'e' (length=1)
11 => string 'f' (length=1)
12 => string 'g' (length=1)
Spero che questo aiuti :-)
fonte
2009-09-08 21:39:21
Ti rendi conto che confrontare i caratteri Unicode non è banale, a seconda del tipo di confronto che desideri? Ad esempio, è possibile scrivere ü come U + 00DC o come U + 0075 U + 0308. – derobert
Sì, lo realizzo. Se fosse diventato un problema, avrei dovuto trasformare l'input in uno dei moduli normali Unicode prima della divisione. – joeforker