参考url:http://www.w3.org/international/questions/qa-forms-utf-8.en.php $result = preg_match(’%^(?: [\x09\x0a\x0d\x20-\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(’%^(?:
[\x09\x0a\x0d\x20-\x7e] # ascii
| [\xc2-\xdf][\x80-\xbf] # non-overlong 2-byte
| \xe0[\xa0-\xbf][\x80-\xbf] # excluding overlongs
| [\xe1-\xec\xee\xef][\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-\xec\xee\xef][\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 contains\tliberal \r\n use of whitespace.\n\n”;
// 首先去掉头尾空格
$str = trim($str);
// 接着去掉两个空格以上的
$str = preg_replace(’/\s(?=\s)/’, ‘’, $str);
// 最后将非空格替换为一个空格
$str = preg_replace(’/[\n\r\t]/’, ‘ ‘, $str);
使用上面的例子可以去掉所有多余的空格。首先使用trim()去头尾空格,接着用preg_replace()去掉重复的空格。
当中的(?=)表示只匹配后面的空格跟随前面的空格的空格。