php 中文分词代码一例
为大家介绍
php 进行中文分词的一段代码,有需要的朋友,可以参考下。
最常见的词语二分法
:
<?php
$str = '这是我的网站 www.jbxue.com!';
//$str = iconv('GB2312','UTF-8',$str);
$result = spStr($str);
print_r($result);
/**
* UTF-8 版 中文二元分词
*/
function spStr($str)
{
$cstr = array();
$search = array(",", "/", "\\", ".", ";", ":", "\"", "!", "~", "`", "^", "(", ")", "?", "-", "\t", "\n", "'",
"<", ">", "\r", "\r\n", "{1}quot;", "&", "%", "#", "@", "+", "=", "{", "}", "[", "]", ":", ")", "(",
".", "。", ",", "!", ";", "“", "”", "‘", "’", "[", "]", "、", "—", " ", "《", "》", "-", "…", "【",
"】",);
$str = <A class=infotextkey href="http://www.jbxue.com/shouce/php5/function.str-
replace.html" target=_blank>str_replace()</A>($search, " ", $str);
preg_match_all("/[a-zA-Z]+/", $str, $estr);
preg_match_all("/[0-9]+/", $str, $nstr);
$str = preg_replace("/[0-9a-zA-Z]+/", " ", $str);
$str = preg_replace("/\s{2,}/", " ", $str);
$str = <A class=infotextkey href="http://www.jbxue.com/shouce/php5/function.explode.html"
target=_blank>explode()</A>(" ", trim($str));
foreach ($str as $s) {
$l = strlen($s);
$bf = null;
for ($i= 0; $i< $l; $i=$i+3) {
$ns1 = $s{$i}.$s{$i+1}.$s{$i+2};
if (<A class=infotextkey href="http://www.jbxue.com/shouce/php5/function.isset.html"
target=_blank>isset()</A>($s{$i+3})) {
$ns2 = $s{$i+3}.$s{$i+4}.$s{$i+5};
if (preg_match("/[\x80-\xff]{3}/",$ns2)) $cstr[] = $ns1.$ns2;
} else if ($i == 0) {