2012-10-26 4 views
1

<title>$title</title>에 제목을 인쇄하고 있습니다. 하지만 적은 문자로 제목을 인쇄하려고합니다. 문제는 내가 선택한 문자의 한계를 인쇄하는 PHP 코드가 있습니다. 그러나 그것은 전체 단어를 완성하기 위해 해결되지 않습니다. 문자가 잘린 단어의 나머지 부분을 인쇄 할 수 있도록 기능이나 방법이 있습니까?글자 수 대신 단어 단위로 자르는 방법

바로 지금 이것은 사용하는 코드입니다.

$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...

의 전체 단어의 나머지를 인쇄 할 나머지 단어들은 불러내시겠습니까?

답변

3

와우이 훨씬 더 간단 보인다 그냥 원래처럼 작동 다시 마지막 공간

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

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

+0

에 트림? 나는이 기능이 존재한다는 것을 몰랐다. – mystycs

+0

완벽하게 작동합니다. – mystycs

+1

함수'strrpos'에는 세 번째 인수가 있습니다.이 인수를 사용하여 한 줄로 단축 할 수도 있습니다 ... 그냥 생각할 수 있습니다 :) 그러나 대신 strpos를 사용해야합니다. –

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; 
} 
?> 
관련 문제