在PHP中剪切UTF8文本 [英] Cut an UTF8 text in PHP

查看:93
本文介绍了在PHP中剪切UTF8文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从数据库中获取UTF8文本,并且我只想显示前$ len个字符(用一个词整理).我尝试了几个选项,但是由于特殊字符(á,é,í,ó等),该功能仍然无法正常工作.

I get UTF8 text from a database, and I want to show only the first $len characters (finishing in a word). I've tried several options but the function still doesn't work because of special characters (á, é, í, ó, etc).

感谢您的帮助!

function text_limit($text, $len, $end='...')
{ 

  mb_internal_encoding('UTF-8');
  if( (mb_strlen($text, 'UTF-8') > $len) ) { 

    $text = mb_substr($text, 0, $len, 'UTF-8');
    $text = mb_substr($text, 0, mb_strrpos($text," ", 'UTF-8'), 'UTF-8');

    ...
  }
}

编辑以添加示例

如果我截断65个字符的文本,它将返回:

If I truncate a text with 65 characters, it returns:

联合国新闻和发展委员会…

Un jardín de estilo neoclásico acorde con el …

如果我更改特殊字符(í,á),则返回:

If I change the special characters (í, á), then it returns:

新古典主义的法国花园……帕拉西奥德……

Un jardin de estilo neoclasico acorde con el Palacio de …

我确定编码,服务器或php有点奇怪;但我不知道!谢谢!

I'm sure there is something strange with the encoding or the server, or php; but I can't figure it out! Thanks!

最终解决方案

我正在使用 UTF8 PHP库现在一切正常...

I'm using this UTF8 PHP library and everything works now...

推荐答案

使用mb_substr.第一个arg要检查的字符串,第二个是起始位置,第三个是长度,最后一个是编码.

use mb_substr. first arg the string to check second is the starting position the third is lenght and last is the encoding.

mb_substr ("String", 0, $len, 'utf-8');

这篇关于在PHP中剪切UTF8文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆