Jump to content

Truncating a string at a space and not in the middle of a word


Gutspiller

Recommended Posts

First, let me state I'm fairly noob when it comes to php, and am merely surviving by finding examples on the Internet.

 

I've spent many hours looking for how to do it, and the closest I've came was this code:

 

$pos = strpos($nocaptitle, ' ', 47);
if ($pos !== false) {
    $nocaptitle = substr($nocaptitle, 0, $pos);

 

This code appears to work how I want it to, except if $nocaptitle is shorter than 47 characters, then I get an error. Can anybody help me finalize this code so it works even if there are fewer than 47 characters?

 

Again, I've looked over the internet, and this is the code that best suited me, other php help sites that offered examples, had higher rated examples than this one, but those examples would think it was OK to cut something "T-mobile" after the T-, the code above is the best I've seen where it keeps words with dashes intact.

 

So while there may be a better way of doing what the above code does, unless it doesn't have that t-mobile problem, I'd prefer you not completely re-write the code as an answer, and just help me fix the code I have. (If you have better code, but it doesn't have this "T-mobile" problem, please post.

 

I'm noob, so if you could post the code that I will need to add or replace, this is what will help. Telling me about what php code to use, but not actually writing it out, will be over my head.

 

Thanks for any help you can provide, on this probably super easy problem for most php coders here.

Link to comment
Share on other sites

I'm not going to fix your code when I already have a function that does what you need. The following function will return a string up-to the number of characters specified. If that will cause the string to break a word (i.e. not on a space) then it truncates the string to the first space before the requested number of characters. It does not truncate on dashes.

 

function truncateString($string, $length, $ellipse='...', $preserveLineBreaks=false)
{
    if(!$preserveLineBreaks)
    {
        //Remove 1 or more line breaks with a single space
        $string = preg_replace("#(\r|\n)+#", " ", $string);
    }
    if (strlen($string) <= $length) { return $string; }
    return trim(array_shift(explode("\f", wordwrap($string, $length, "\f")))) . $ellipse;
}

$nocaptitle = truncateString($nocaptitle, 47);

 

The $ellipse parameter is optional (default is '...') and will be concatenated to the string - if it is truncated. If you don't want it pass an empty string as the 3rd parameter. The 4th parameter is to specify whether line breaks in the input should be preserved. The defaul tis false. SO, if a multi-line string is passed to the function, the line breaks will be replaces with spaces. Then the truncation is applied.

Link to comment
Share on other sites

When I replace my existing chunk of code with that, I get this error:

 

"Fatal error: Cannot redeclare truncatestring() (previously declared in /home/threedn/public_html/templates/feeds.php:29) in /home/threedn/public_html/templates/feeds.php on line 29"

 

Line 29 ends up being the very first line of your code. I think I see that the error is trying to process your code again for the second (of many) instances I need to use it on a single page. Can a fix be supplied to correct this issue, or is the problem where I'm placing the code?

Link to comment
Share on other sites

The problem is you have apparently copy/pasted the function many times. You only need to create the function ONCE, then call it as many times as you need it.

 

Example:

function truncateString($string, $length, $ellipse='...', $preserveLineBreaks=false)
{
    if(!$preserveLineBreaks)
    {
        //Remove 1 or more line breaks with a single space
        $string = preg_replace("#(\r|\n)+#", " ", $string);
    }
    if (strlen($string) <= $length) { return $string; }
    return trim(array_shift(explode("\f", wordwrap($string, $length, "\f")))) . $ellipse;
}

$nocaptitle = truncateString($nocaptitle, 47);

$somestring = truncateString($nocaptitle, 47);

$anotherstring = truncateString($anotherstring, 47);

Link to comment
Share on other sites

I only pasted your code once, here's my entire code for that section:

 


<div class="<?=$template['classname']?>">
<h2>
<?	if ($template['permalink']){	?><a href="<?=$template['permalink']?>" target="_new"><img src="<?=$template['favicon']?>" width="16" height="16" border="0" style="vertical-align:middle;" onerror="this.style.display='none'"/><?	}	?>	
<? 
$newurl=parse_url($template['permalink'])
?>
<?= str_replace ( array("www.",".com",".net",".org",".cc",".ru",".co.uk",".de",".us",".gov",".biz",".dk"), "", $newurl['host'] )?>
<?	if ($template['permalink']){	?></a><?	}	?>	
</h2>
<div style="background-image:url('images/alternating.gif');background-repeat:repeat-x;">
<ul>

<?	foreach($template['rows'] as $row){ ?>

<?

$nohtmltitle = strip_tags($row['title']);
$newtitle = preg_replace('/[^a-zA-Z0-9\&;"\,#.\-\$ ]/','',$nohtmltitle);

   $nocaptitle = preg_replace_callback(
   '/\b\p{Lu}{3,}\b/u',
        create_function(
            '$matches',
            'return ucwords(strtolower($matches[0]));'
        ),
        $newtitle
    );


function truncateString($string, $length, $ellipse='...', $preserveLineBreaks=false)
{
    if(!$preserveLineBreaks)
    {
        //Remove 1 or more line breaks with a single space
        $string = preg_replace("#(\r|\n)+#", " ", $string);
    }
    if (strlen($string) <= $length) { return $string; }
    return trim(array_shift(explode("\f", wordwrap($string, $length, "\f")))) . $ellipse;
}

$nocaptitle = truncateString($nocaptitle, 47);

?>

	<li class="feeditem">
		<?=$row['new']?><a href="<?=$row['permalink']?>" target=_new><?= $nocaptitle ?><div class="tooltip left silver"><div class="tooltiptitle"><?= preg_replace("/[^[:alnum:][:punct:][:space:]]/","", $row['title'] )?></div><div style="max-width: 282px; overflow: hidden;"><?= preg_replace("/[^[:alnum:][:punct:][:space:]]/","", $row['desc'] )?></div></div></a>
	</li>

<?	}	?>
</ul>
</div>
</div>

 

Any ideas why it's not working?

Link to comment
Share on other sites

You get "Cannot redeclare XX function blah blah... " errors when you... well... redeclare a function. What that means is you must have another function names truncatestring(). Perhaps in an included page or something.

 

Also, just as a coding style preference, I like to put my functions at the top of my page, rather than at an arbitrary point in the middle of the script. Makes it a little easier to find as you add more and more code and functions to your page. Not saying what you have is bad/incorrect but just wanted to let you know

Link to comment
Share on other sites

Can I simply rename truncatestring to something else in all spots of this new code for it to work, or is it a direct php function that if renamed, php wouldn't know what to do with it?

 

Why would you want to rename the same function with different names. Just create the function ONCE, then use it multiple times. This is programming 101. In my second post I even provided an example of how you would reuse the function multiple times.

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.