質問

文字列を単語全体に切り捨てる次の関数を考え出そうとしています(可能であれば、それ以外の場合はcharに切り捨てるはずです):

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, '...');

彼らは両方ともそれがそのまま働きますが、私が2番目を落とすと動作します preg_replace() 次のことがわかります。

iñtërnâtiônàlizætiøn_and_then_the_quick_brown_fox_jumped_overly_the_lazy_dogそしてある日、怠zyな犬は貧しいキツネを叩きました。

使えない substr() バイトレベルでのみ動作し、アクセスできないため mb_substr() ATM、私は最初の正規表現に参加しようとする試みを何度か試みましたが、成功しませんでした。

SMSを助けてください、私はこれに1時間近く苦労してきました。


編集:申し訳ありませんが、私は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, 、私はそのケースがネッカリーになるとは感じませんでした。

他のヒント

ワードラップの使用を検討しましたか? (http://us3.php.net/wordwrap)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top