参考URL:http://www.w3.org/International/questions/qa-forms-utf-8.en.php $result = preg_match(’%^(?: [x09x0Ax0Dx20-x7E] # ASCII | [xC2-xDF][x80-xBF] # non-overlong 2-byte | xE0[xA0-xBF][x80-xBF] # excluding overlongs | [xE1
参考URL:http://www.w3.org/International/questions/qa-forms-utf-8.en.php
$result = preg_match(’%^(?:
[x09x0Ax0Dx20-x7E] # ASCII
| [xC2-xDF][x80-xBF] # non-overlong 2-byte
| xE0[xA0-xBF][x80-xBF] # excluding overlongs
| [xE1-xECxEExEF][x80-xBF]{2} # straight 3-byte
| xED[x80-x9F][x80-xBF] # excluding surrogates
| xF0[x90-xBF][x80-xBF]{2} # planes 1-3
| [xF1-xF3][x80-xBF]{3} # planes 4-15
| xF4[x80-x8F][x80-xBF]{2} # plane 16
)*$%xs’, $string);
如果$result为真,则是UTF-8编码的字符串,否为ANSI
以上面为条件,匹配出字符串中的中文
if ($result) {
preg_match_all(“/[xE1-xECxEExEF][x80-xBF]{2}/”, $str, $arr);
print_r($arr[0]);
} else {
preg_match_all(“/[x80-xFF]./”, $str, $arr);
print_r($arr[0]);
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
PHP清除空格
日常我们处理数据时经常会产生额外的空格,如果你想进行诸如比较字符串时,就会引致问题;同时也浪费额外的储存空间。
如何除掉空格?也许你首先会想到PHP内建函数trim()。没错,它处理字符的始末部分确实有效,但是,这种情况下它就办不到了:将多个空格变为一个空格,将空格变为有序的规则的队列等等…
于是,正则表达式就派上用场了。看看下面的代码:
$str = ” This line containstliberal rn use of whitespace.nn”;
// 首先去掉头尾空格
$str = trim($str);
// 接着去掉两个空格以上的
$str = preg_replace(’/s(?=s)/’, ‘’, $str);
// 最后将非空格替换为一个空格
$str = preg_replace(’/[nrt]/’, ‘ ‘, $str);