簡體   English   中英

合並兩個正則表達式來截斷字符串中的單詞

[英]Merging two Regular Expressions to Truncate Words in Strings

我試圖提出以下函數將字符串截斷為整個單詞(如果可能,否則它應截斷為字符):

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,我已經多次嘗試將第二個正則表達式加入到第一個正則表達式但沒有成功。

請幫助短信,我一直在努力這一近一個小時。


編輯:對不起,我已經醒了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愚弄了 - 我應該把它留到另一天,現在睡一覺。 今天關閉。

在漫長的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 ,因此我覺得不需要這種情況。

你考慮過使用wordwrap嗎? http://us3.php.net/wordwrap

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM