2017-02-17 1 views
1

4単語または5単語に達したら、単語を切り取り、 "..."を追加するにはどうすればよいですか?PHP:単語を切り取り、 "..."を追加するにはどうすればいいですか?

以下のコードでは、私はキャラクターベースのカッコいい単語を作ったが、私は今言葉でそれを必要としている。

現在、私はこの種のコードがあります

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-省略記号/ – 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()機能によって行われます。

str_replace('your word', '...', $variable); 

はその記事を読みました。

<?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; 
?> 
関連する問題