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?

Link to comment
Share on other sites

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";
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.