-1

我有一个从数据库中检索的字符串,我想计算不带空格的字符串的长度,但它显示的长度值更大(比实际计数大 21 个字符)我删除了制表符和换行符以及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;
}

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

<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>
4

2 回答 2

4

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

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

更改 \r\n 和 \n 使 str_replace 不会从 \r\n 中删除 \n,而只留下 \r。

干杯。

于 2013-01-02T10:00:16.850 回答
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");
于 2012-10-31T14:14:33.750 回答