2010-04-21 31 views
7

我试图想出以下功能截断字符串全字(如果可能的话,否则它应该截断到个字符):合并两个正则表达式来截断字符串里的单词

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愚弄 - 我应该把它留到另一天,现在睡一觉。今天关闭。

+3

可怜的狐狸。 _____ – kennytm 2010-04-21 13:15:31

+0

为什么不使用'trim'来摆脱尾随的空白? – Jens 2010-04-21 13:34:27

+3

唤醒40小时并处理正则表达式。 +1可怜的票。 – 2010-04-21 13:36:10

回答

3

也许我可以一个漫长的夜晚正则表达式的噩梦后,给你一个快乐的上午:

'~^(.{1,' . intval($limit) . '}(?<=\S)(?=\s)|.{'.intval($limit).'}).*~su' 

沸腾了下去:

​​

你总是可以添加|$到底(?=\s)但由于您的代码已经检查字符串的长度是否比$limit更长,我不觉得这种情况是必要的。

+0

更多“愉快的下午”,但感谢gnarf!我去睡觉有一个印象,我将不得不使用lookahead或只使用trim()'。再次感谢! – 2010-04-22 18:00:43

0

您是否考虑过使用wordwrap? (http://us3.php.net/wordwrap

+1

是的,对于大字符串,它的速度较慢,不适用于多字节字符。 – 2010-04-22 18:15:20

相关问题