2010-11-27 63 views
0

我如何从$ xb substr 20个字符并获得完整的单词?Php substr整个单词

$xbio = 'word1 ord2 word3 word4 and so on'; 
echo ''.substr($xbio, 0, 20).'...'; 

TY

发现这个搜索计算器 - 告诉我,你怎么想请:

<? $xbio = preg_replace('/\s+?(\S+)?$/', '', substr($xbio, 0, 50)); ?> 
+1

看看http://php.net/manual/en/function.wordwrap.php – Mchl 2010-11-27 14:41:37

+0

你必须先定义一个术语“单词”。 PHP不知道你的意思。 – 2010-11-28 13:30:24

回答

0
preg_match('/^([a-zA-Z0-9 ]{1,20})\\b/', $xbio, $matches); 
echo $matches[1]; 
+0

你为什么要用{1,30}`? – 2010-11-27 14:57:18

0

这是我使用这种任务的功能:

function truncate($str, $maxLength, $append = '...') { 
    if (strlen($str) > $maxLength) { 
     $str = substr($str, 0, $maxLength); 
     $str = preg_replace('/\s+.*?$/', '', $str); // this line is important for you 
     $str = trim($str); 
     $str .= $append: 
    } 

    return $str; 
} 
1

这是我总是使用的功能:

# advanced substr 
function gen_string($string,$min) { 
    $text = trim(strip_tags($string)); 
    if(strlen($text)>$min) { 
     $blank = strpos($text,' '); 
     if($blank) { 
      # limit plus last word 
      $extra = strpos(substr($text,$min),' '); 
      $max = $min+$extra; 
      $r = substr($text,0,$max); 
      if(strlen($text)>=$max) $r=trim($r,'.').'...'; 
     } else { 
      # if there are no spaces 
      $r = substr($text,0,$min).'...'; 
     } 
    } else { 
     # if original length is lower than limit 
     $r = $text; 
    } 
    return $r; 
}