PHP string / kelime işlem soru

3 Cevap php

Ben şu cümle var diyelim:

A quick brown fox jumped over a lazy dog.

Ancak ben sadece 25 karakter o cümlede izin verilebilir ki, bir sınırı var. Bu gibi bir şey ile bana bırakabilir:

A quick brown fox jum

Ancak, bu cümle herhangi bir gramer mantıklı değil, ben 25 karakter sınırı içinde kalırken izin verebilirsiniz son sözcüğü bulmak için tercih ediyorum. Bu bize gibi bir şey verecek:

A quick brown fox

Which will be less than the 25 char limit, however it makes more grammatical sense. I.e the word isn't broken up, we have the maximum number of comprehensible words while staying in the limit.

Nasıl bir dize alacak bir fonksiyon, ve örneğin 25 gibi bir karakter sınırı kodu, ve dize sınırını aşarsa, olası kelimelerin maksimum sayıda dize döndürür edebilir?

3 Cevap

Bu regex kullanarak yeterince kolay:

function first_few_words($text, $limit) {
    // grab one extra letter - it might be a space
    $text = substr($text, 0, $limit + 1);
    // take off non-word characters + part of word at end
    $text = preg_replace('/[^a-z0-9_\-]+[a-z0-9_\-]*\z/i', '', $text);
    return $text;
}

echo first_few_words("The quick brown fox jumps over the lazy dog", 25);

Bu uygulama bazı ekstra özellikleri:

  • Ayrıca linebreaks ve sekmeler de kelimeleri böler.
  • Karakteri 25 biter ekstra bir sözcüğü kaydeder.

Edit: regex değişti sadece harf, rakam, '_' ve böylece '-' kelimesi karakterler kabul edilir.

<?php
    function wordwrap_explode($str, $chars)
    {
        $code = '@@@';
        return array_shift(explode($code, wordwrap($str, $chars, $code)));
    }
    echo wordwrap_explode('A quick brown fox jumped over a lazy dog.', 25);
?>

Çıktı:

A quick brown fox jumped

You cant try adapting this function. I took The idea from the php site and adapted it to my needs. It takes the "head" and "tail" of a string and reduces the string (considering words) to the given length. For your needs yo may be ok striping all the "tail" part of the function.

function strMiddleReduceWordSensitive ($string, $max = 50, $rep = ' [...] ') {
$string=nl2space(utf8decode($string));
$strlen = mb_strlen ($string);

if ($strlen <= $max)
   return $string;

$lengthtokeep = $max - mb_strlen($rep);
$start = 0;
$end = 0;

if (($lengthtokeep % 2) == 0) {
   $length = $lengthtokeep / 2;
   $end = $start;
} else {
   $length = intval($lengthtokeep / 2);
   $end = $start + 1;
}
$tempHead = mb_strcut($string, 0, $length);
$headEnd = strrpos($tempHead, ' ')+1;
$head = trim(mb_strcut($tempHead, 0, $headEnd));

$tempTail = mb_strcut($string, -$length);
$tailStart = strpos($tempTail, ' ')+1;
$tail = trim(mb_strcut($tempTail, $tailStart));
//p($head);
//p($tail);
return $head . $rep . $tail;

}