Strlen没有提供正确的输出

时间:2012-10-31 14:12:43

标签: php string strlen

我有一个从数据库中检索的字符串,我想计算没有空格的字符串的长度,但是它显示了一个更大的长度值(比实际计数大21个字符)我删除了tab和换行符还有php和html标签,但没有结果!我已经尝试了w3schools php参考文件中的几乎所有功能,但我无法找到任何成功。我也观察到,如果我不从数据库中检索值并输入如下:

$string = "my string";

我得到正确的长度,请帮助我。这是代码:

if($res_tutor[0]['tutor_experience']){
        $str = trim(strip_tags($res_tutor[0]['tutor_experience']));
            $str = $this->real_string($str);
            $space = substr_count($str, ' ');
            $experience  = strlen($str) -  $space;


function real_string($str)
{
    $search  = array("\t","\n","\r\n","\0","\v");
    $replace = array('','','','','');
    $str = str_replace($search,$replace,$str);
    return $str;
}

这是数据库中的字符串,但正如您在上面所看到的,我已使用strip_tags()删除了所有php和html标记:

<span class=\"experience_font\">You are encouraged to write a short description of yourself, teaching experience and teaching method. You may use the guidelines below to assist you in your writing.<br />
   <br />
   .Years of teaching experience<br />
   .Total number of students taught<br />
   .Levels &amp; subjects that you have taught<br />
   .The improvements that your students have made<br />
   .Other achievements/experience (Relief teaching, a tutor in a tuition centre, Dean&#39;s list, scholarship, public speaking etc.)<br />
   .For Music (Gigs at Esplanade, Your performances in various locations etc.)</span><br />
   &nbsp;</p>

当我打印它时,它显示为:

<span class=\"experience_font\">You are encouraged to write a short description of yourself, teaching experience and teaching method. You may use the guidelines below to assist you in your writing.<br />
   <br />
   .Years of teaching experience<br />
   .Total number of students taught<br />
   .Levels &amp; subjects that you have taught<br />
   .The improvements that your students have made<br />
   .Other achievements/experience (Relief teaching, a tutor in a tuition centre, Dean&#39;s list, scholarship, public speaking etc.)<br />
   .For Music (Gigs at Esplanade, Your performances in various locations etc.)</span><br />
   &nbsp;</p>

2 个答案:

答案 0 :(得分:4)

@Svetilo,不要粗鲁只想发布我的发现,你的str_replace工作得非常好,除了我仍然按照你现在的顺序输出不正确的值,我发现以下工作完美无缺

$string = str_replace(array("\t","\r\n","\n","\0","\v"," "),'', $string);
mb_strlen($string, "UTF-8");

改变\ r \ n&amp; \ n使str_replace不会从\ r \ n中删除\ n,只留下\ r。

干杯。

答案 1 :(得分:3)

尝试使用mb_strlen。 http://php.net/manual/en/function.mb-strlen.php 它更精确。

mb_strlen($str,"UTF-8") 

UTF-8是您的默认编码... 要删除所有的自由空间,请尝试类似的东西......

 $string = str_replace(array("\t","\n","\r\n","\0","\v"," "),"",$string);
 mb_strlen($string, "UTF-8");