0

I have this function to truncate strings longer than a specified parameter. It works with all the strings I passed to it since now.But when I test with the following string I have problems:

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

It says:

"Undefined variable:string"  

the function is:

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; 
}

This is how I call It:

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

Where am I wrong?

SOLVED: As you guys make me notice The returned $string value wasnt defined outside of

if($post!==' ')

So I added an else statement defining the $string as:

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

Thanks Luca

luca
  • 36,606
  • 27
  • 86
  • 125
  • Where is $string defined that's being passed into limitString? – onteria_ May 17 '11 at 15:59
  • If I understand correctly what you're trying to do with this function, have you considered using: http://php.net/manual/en/function.wordwrap.php ? – Yoshi May 17 '11 at 16:12
  • possible duplicate of [Truncate a multibyte String to n chars](http://stackoverflow.com/questions/2154220/truncate-a-multibyte-string-to-n-chars) – Gordon May 17 '11 at 16:24

2 Answers2

2

The problem is that there is a case in which your $string variable will never be defined, as in:

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; 
}

The solution is to define $string at the top of your function:

$string = "";

So that your return statement will always return something.

Brian Driscoll
  • 19,373
  • 3
  • 46
  • 65
1

This will happen when the following tests fail:

if(strlen($message)<$position)

and

if($post !=" ")

$string is defined only in those two blocks. To fix this, you should define $string before the conditional statements:

$string=$message;
if(strlen($message)<$position) {
    ....
George Cummins
  • 28,485
  • 8
  • 71
  • 90