簡體   English   中英

在 PHP 中縮短文本字符串

[英]Shorten a text string in PHP

有沒有辦法在 PHP 中修剪文本字符串,使其具有一定數量的字符? 例如,如果我有字符串:

$string = "this is a string";

我怎么能修剪它說:

$newstring = "this is";

這是我到目前為止所擁有的,使用chunk_split() ,但它不起作用。 有人可以改進我的方法嗎?

function trimtext($text)
{
$newtext = chunk_split($text,15);
return $newtext;
}

我也看了這個問題,但我真的不明白。

if (strlen($yourString) > 15) // if you want...
{
    $maxLength = 14;
    $yourString = substr($yourString, 0, $maxLength);
}

會做的工作。

在這里看看。

您沒有說出這樣做的原因,而是考慮您想要實現的目標。 這是一個用於逐個單詞地縮短字符串的功能,該字符串的末尾添加或不添加省略號:

function limitStrlen($input, $length, $ellipses = true, $strip_html = true) {
    //strip tags, if desired
    if ($strip_html) {
        $input = strip_tags($input);
    }

    //no need to trim, already shorter than trim length
    if (strlen($input) <= $length) {
        return $input;
    }

    //find last space within length
    $last_space = strrpos(substr($input, 0, $length), ' ');
    if($last_space !== false) {
        $trimmed_text = substr($input, 0, $last_space);
    } else {
        $trimmed_text = substr($input, 0, $length);
    }
    //add ellipses (...)
    if ($ellipses) {
        $trimmed_text .= '...';
    }

    return $trimmed_text;
}
function trimtext($text, $start, $len)
{
    return substr($text, $start, $len);
}

您可以這樣調用函數:

$string = trimtext("this is a string", 0, 10);

將返回:

This is a

substr將單詞切成兩半。 同樣,如果單詞包含UTF8字符,則其行為不正確。 所以最好使用mb_substr:

$string = mb_substr('word word word word', 0, 10, 'utf8').'...';

substr我們可以根據需要substr一部分字符串,該字符串完全由字符組成。

你可以用這個

substr()

獲取子字符串的函數

如果要獲取包含一定數量字符的字符串,可以使用substr,即

$newtext = substr($string,0,$length); 

其中$ length是新字符串的給定長度。

如果您想要前10個字的摘要(您可以在$ text中使用html,在腳本之前為strip_tags),請使用以下代碼:

preg_match('/^([^.!?\s]*[\.!?\s]+){0,10}/', strip_tags($text), $abstract);
echo $abstract[0];

我的函數有一定長度,但是我喜歡使用它。 我將字符串int轉換為數組。

function truncate($text, $limit){
    //Set Up
    $array = [];
    $count = -1;
    //Turning String into an Array
    $split_text = explode(" ", $text);
    //Loop for the length of words you want
    while($count < $limit - 1){
      $count++;
      $array[] = $split_text[$count];
    }
    //Converting Array back into a String
    $text = implode(" ", $array);

    return $text." ...";

  }

或者,如果文本來自編輯器,並且您要剝離HTML標記。

function truncate($text, $limit){
    //Set Up
    $array = [];
    $count = -1;
    $text = filter_var($text, FILTER_SANITIZE_STRING);

    //Turning String into an Array
    $split_text = preg_split('/\s+/', $text);
    //Loop for the length of words you want
    while($count < $limit){
      $count++;
      $array[] = $split_text[$count];
    }

    //Converting Array back into a String
    $text = implode(" ", $array);

    return $text." ...";

  }

使用省略號 (...) 僅當更長時 - 並處理特殊的語言特定字符:

mb_strlen($text,'UTF-8') > 60 ? mb_substr($text, 0, 60,'UTF-8') . "…" : $text;

暫無
暫無

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

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