合并两个正则表达式来截断字符串中的单词

时间:2010-04-21 12:35:27

标签: php regex string truncate multibyte

我正在尝试使用以下函数将字符串截断为整个单词(如果可能,否则它应截断为字符):

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() ATM,我已尝试多次尝试将第二个正则表达式加入第一个正则表达式但没有成功。

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

2 个答案:

答案 0 :(得分:3)

也许在经过漫长的RegExp噩梦之后,我可以给你一个愉快的早晨:

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

将其煮沸:

^      # Start of String
(       # begin capture group 1
 .{1,x} # match 1 - x characters
 (?<=\S)# lookbehind, match must end with non-whitespace 
 (?=\s) # lookahead, if the next char is whitespace, match
 |      # otherwise test this:
 .{x}   # got to x chars anyway.
)       # end cap group
.*     # match the rest of the string (since you were using replace)

您始终可以将|$添加到(?=\s)的末尾,但由于您的代码已经检查字符串长度超过$limit,我感觉不到这种情况将是必要的。

答案 1 :(得分:0)

你考虑过使用wordwrap吗? (http://us3.php.net/wordwrap