2011-05-17 54 views
0

我有此函數截斷比指定參數長的字符串。 它與我通過它,因爲now.But當我用下面的字符串測試的所有字符串我有問題:截斷函數中的「未定義的變量」通知,但只有當某些字符串被傳入時

Fifth post is the worst ever.Dont you believe?Just read it! 

它說:

"Undefined variable:string" 

的功能是:

public function limitString($message,$position,$limitString) 
{ 

    if(strlen($message)<$position) 
    $string=$message; 

    else 
    { 
    $post = substr($message,$position,1); // Find what is the last character displaying. 

    if($post !=" ") 
    { 

     for($i=$position-1;$i>0;$i--) 
     { 
      $post = substr($message,$i,1); 
      if ($post ==" ") 
      { 
      break; 
      } 
     } 

     $string=substr($message,0,$i).$limitString; 
    } 

    } 

    return $string; 
} 

這是我怎麼稱呼它:

limitString($string,33,"...") 

我錯在哪裏?

解決:正如你們讓我看到的

if($post!==' ') 

之外定義返回$字符串值wasnt所以我添加定義$字符串作爲else語句:

$string=substr($message,0,$position).$limitString; 

謝謝 Luca

+0

其中是$字符串定義它被傳遞到limitString? – 2011-05-17 15:59:55

+0

如果我正確理解你想用這個函數做什麼,你有沒有考慮使用:http://php.net/manual/en/function.wordwrap.php? – Yoshi 2011-05-17 16:12:33

+0

[將多字節字符串截斷爲n個字符](http://stackoverflow.com/questions/2154220/truncate-a-multibyte-string-to-n-chars) – Gordon 2011-05-17 16:24:04

回答

2

的問題是,有在你的$string變量都不會被定義的情況下,如:

public function limitString($message,$position,$limitString) 
{ 

if(strlen($message)<$position) 
$string=$message; 

else 
{ 
$post = substr($message,$position,1); // Find what is the last character displaying. 
//$string is not defined here. 
if($post !=" ") 
{ 

    for($i=$position-1;$i>0;$i--) 
    { 
     $post = substr($message,$i,1); 
     if ($post ==" ") 
     { 
     break; 
     } 
    } 

    $string=substr($message,0,$i).$limitString; 
} 
    //$string is not defined here 
} 

return $string; 
} 

的解決方法是在你的函數的頂部定義$字符串:

$string = "";

使您return聲明WIL我總是返回東西

1

當下列測試失敗時會發生這種情況:

if(strlen($message)<$position) 

if($post !=" ") 

$串僅被定義在這兩個區塊。爲了解決這個問題,你應該在條件語句之前定義$字符串:

$string=$message; 
if(strlen($message)<$position) { 
    ....