Home  >  Article  >  Backend Development  >  怎么提取中文字符,并算出该字符的位置

怎么提取中文字符,并算出该字符的位置

WBOY
WBOYOriginal
2016-06-13 11:10:481073browse

如何提取中文字符,并算出该字符的位置?
字符串1:一?二? //中文的问号
字符串2:?一?二  //英文的问号
字符串3:一 二  //中间有空格

php如何匹配出以上字符串里的中文文字?并求出该字符的位置
搞了半天搞不定,以下我的代码,大家别笑话

$k1 = "";
$k2 = "";
$k3 = "";
$k4 = "";
if(ord(substr($this->Keywords,1,1))>127)
{
$k1 = substr($this->Keywords,0,2);
}else {$k1=false;}
if(ord(substr($this->Keywords,2,1))>127)
{
$k2 = substr($this->Keywords,2,2);
}else {$k2=false;}
if(ord(substr($this->Keywords,3,1))>127)
{
$k3 = substr($this->Keywords,3,2);
}else {$k3=false;}
if(ord(substr($this->Keywords,4,1))>127)
{
$k4 = substr($this->Keywords,4,2);
}else {$k4=false;}


------解决方案--------------------
那要看是utf8还是gb2312.
我看你的是utf8的检测。utf8中文占3字节,头字节>127。
str_split后,检测到大于127的,后面2个字节也获取即可。
------解决方案--------------------
$k1 = mb_substr($this->Keywords, 0, 1, "UTF-8");

------解决方案--------------------
<br />$str	= '一?二?';<br />$arr	= preg_split('/\?<br><font color='#FF8000'>------解决方案--------------------</font><br>?<br><font color='#FF8000'>------解决方案--------------------</font><br> /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);<br />print_r($arr);<br />//得到二维数组,$arr[$i][0] 匹配满足的字符,$arr[$i][1]匹配位置<br />//这个位置是strlen,如果中文算一个字符,只需要截取前面那段字符,用mb_strlen即可<br /><br />
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn