Jump to content

[SOLVED] breaking up a string based on a limit of chars?


tjhilder

Recommended Posts

Hi, I've tried creating a small function that breaks up a string if longer than 15 characters but for some reason it's output is wrong.

	function str_break($string)
{
	$str_limit = 15;
	if(strlen($string) >= $str_limit)
	{
		echo substr($string, 0, 15) . "..";
	}
	else
	{
		echo $string;
	}
        }

 

and then outputs this way:

<?php echo $image_id . ": " . str_break($image) . "\n"; ?>

 

but it outputs as if it is coded this way:

<?php echo str_break($image) . $image_id . ": \n"; ?>

 

what's wrong with it?

Don't use echo within functions, use return (which instantly breaks out of a function not executing any more code within the function):

 

<?php
function str_break($string){
$str_limit = 15;
if(strlen($string) > $str_limit)
	return substr($string, 0, 15) . "..";
return $string;
}
echo $image_id . ": " . str_break($image) . "\n";
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.