我试图想出以下功能截断字符串全字(如果可能的话,否则它应该截断到个字符):合并两个正则表达式来截断字符串里的单词
function Text_Truncate($string, $limit, $more = '...')
{
$string = trim(html_entity_decode($string, ENT_QUOTES, 'UTF-8'));
if (strlen(utf8_decode($string)) > $limit)
{
$string = preg_replace('~^(.{1,' . intval($limit) . '})(?:\s.*|$)~su', '$1', $string);
if (strlen(utf8_decode($string)) > $limit)
{
$string = preg_replace('~^(.{' . intval($limit) . '}).*~su', '$1', $string);
}
$string .= $more;
}
return trim(htmlentities($string, ENT_QUOTES, 'UTF-8', true));
}
这里有一些测试:
// Iñtërnâtiônàlizætiøn and then the quick brown fox... (49 + 3 chars)
echo dyd_Text_Truncate('Iñtërnâtiônàlizætiøn and then the quick brown fox jumped overly the lazy dog and one day the lazy dog humped the poor fox down until she died.', 50, '...');
// Iñtërnâtiônàlizætiøn_and_then_the_quick_brown_fox_... (50 + 3 chars)
echo dyd_Text_Truncate('Iñtërnâtiônàlizætiøn_and_then_the_quick_brown_fox_jumped_overly_the_lazy_dog and one day the lazy dog humped the poor fox down until she died.', 50, '...');
他们都工作,因为它是,但如果我把第二preg_replace()
我得到如下:
Iñtërnâtiônàlizætiøn_and_then_the_quick_brown_fox_jumped_overly_the_lazy_dog 有一天懒狗弓起的 可怜的狐狸,直到她去世....
我不能使用substr()
,因为它只能在字节级和我没有获得mb_substr()
自动柜员机,我已经做了几次尝试加入第一个正则表达式,但没有成功。
请帮助S.M.S.,我一直在为此奋斗了近一个小时。
编辑:对不起,我已经清醒40小时,我无耻地错过了这一点:
$string = preg_replace('~^(.{1,' . intval($limit) . '})(?:\s.*|$)?~su', '$1', $string);
不过,如果有人有更优化的正则表达式(或一个忽略尾随空格),请分享一下:
"Iñtërnâtiônàlizætiøn and then "
"Iñtërnâtiônàlizætiøn_and_then_"
编辑2:我仍然无法摆脱尾随空白的,有人可以帮我吗?编辑3:好的,我的编辑没有真正起作用,我被RegexBuddy愚弄 - 我应该把它留到另一天,现在睡一觉。今天关闭。
可怜的狐狸。 _____ – kennytm 2010-04-21 13:15:31
为什么不使用'trim'来摆脱尾随的空白? – Jens 2010-04-21 13:34:27
唤醒40小时并处理正则表达式。 +1可怜的票。 – 2010-04-21 13:36:10