1

タイトルをに印刷してい<title>$title</title>ます。しかし、私はより少ない文字でタイトルを印刷しようとしています。問題は、選択した文字数の制限でそれを印刷するphpコードを持っていることです。しかし、それは単語全体を終えるために解決しません。文字で切り取られた残りの単語を印刷する機能や方法はありますか?

現在、これはimが使用しているコードです。

$title="Website.com | ". stripslashes($content['text']);
if ($title{70}) {
  $title = substr($title, 0, 69) . '...';
}else{
  $title = $title;
}

だからそれは次のようなものを印刷しますWebsite.com | Here is your sent...

しかし、たとえば単語全体の残りを印刷したいWebsite.com | Here is your sentence...

コードを編集するにはどうすればよいですか、または単語の残りの部分を呼び出すことができる関数はありますか?

4

2 に答える 2

3

最後のスペースに戻す

 $title = substr($title, 0, 69) ;
 $title = substr($title, 0, strrpos($title," ")) . '...';

http://php.net/manual/en/function.strrpos.php

于 2012-10-26T02:24:18.613 に答える
0
<?php
/**
* trims text to a space then adds ellipses if desired
* @param string $input text to trim
* @param int $length in characters to trim to
* @param bool $ellipses if ellipses (...) are to be added
* @param bool $strip_html if html tags are to be stripped
* @return string 
*/
function trim_text($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), ' ');
$trimmed_text = substr($input, 0, $last_space);

//add ellipses (...)
if ($ellipses) {
    $trimmed_text .= '...';
}

return $trimmed_text;
}
?>
于 2012-10-26T02:23:47.257 に答える