2017-02-17 50 views
1

如何剪切單詞並在達到4或5個單詞後添加「...」?PHP:如何剪切單詞並添加「...」

下面的代碼表示我做了基於字符的單詞cutb,但現在我需要它通過單詞。

目前我有這樣的代碼:

if(strlen($post->post_title) > 35) 
    { 
    $titlep = substr($post->post_title, 0, 35).'...'; 
    } 
    else 
    { 
    $titlep = $post->post_title; 
    } 

,這是標題的輸出:

if ($params['show_title'] === 'true') { 
    $title = '<h3 class="wp-posts-carousel-title">'; 
    $title.= '<a href="' . $post_url . '" title="' . $post->post_title . '">' . $titlep . '</a>'; 

    $title.= '</h3>'; 
    } 
+2

我建議使用CSS,並把它在客戶端,這是一個演示文稿的問題:https://開頭的CSS-技巧.com/snippets/css/truncate-string-with-ellipsis/ – user2182349

+0

同意user2182349。雖然下面提供的純粹的PHP答案可以工作,但CSS解決方案會更加理想和靈活。 – cteski

+0

NAH ......在我剪下4-5個字後,它必須有「...」......但是非常感謝你的建議。我只是需要這是合乎邏輯的。 –

回答

1

通常情況下,我會爆炸的身體,然後拉出第一個X字符。

$split = explode(' ', $string); 

$new = array_slice ($split, 0 ,5); 

$newstring = implode(' ', $new) . '...'; 

只知道,這種方法很慢。

1

變#1

function crop_str_word($text, $max_words = 50, $sep = ' ') 
{ 
    $words = split($sep, $text); 

    if (count($words) > $max_words) 
    { 
     $text = join($sep, array_slice($words, 0, $max_words)); 
     $text .=' ...'; 
    } 

    return $text; 
} 

變#2

function crop_str_word($text, $max_words, $append = ' …') 
{ 
     $max_words = $max_words+1; 

     $words = explode(' ', $text, $max_words); 

     array_pop($words); 

     $text = implode(' ', $words) . $append; 

     return $text; 
} 

變#3

function crop_str_word($text, $max_words) 
{ 
    $words = explode(' ',$text); 

    if(count($words) > $max_words && $max_words > 0) 
    { 
     $text = implode(' ',array_slice($words, 0, $max_words)).'...'; 
    } 

    return $text; 
} 

via

+2

貸方應歸功於:http://api.co.ua/trim-a-string-of-php-on-number-of-words.html – nogad

0

在WordPress的這個功能是由wp_trim_words()函數來完成。

<?php 
    if(strlen($post->post_title) > 35) 
    { 
     $titlep = wp_trim_words($post->post_title, 35, '...'); 
    } 
    else 
    { 
     $titlep = $post->post_title; 
    } 
?> 

如果您在使用PHP然後編寫如下代碼來執行此功能:

<?php 
    $titlep = strlen($post->post_title) > 35 ? substr($post->post_title, 0, 35).'...' : $post->post_title; 
?> 
相關問題