Log in

View Full Version : How can I specify the length of the string more precisely?



qwikad.com
10-24-2013, 12:41 PM
I am using this to shorten long titles:




<?php

$title = $row['adtitle'];
if (strlen($title) > 50) {
$title = substr($title, 0, 50).'...';
}
echo $title;

?>



The thing is it shortens them this way:

Selling housing in OH. Stop by to check it ou...

Make money working from home. Best opport...

I want it to shorten them right before the last word, so that it would look like this:

Selling housing in OH. Stop by to check it...

Make money working from home. Best...

Any ideas how to do that?

Thanks!

jscheuer1
10-24-2013, 01:36 PM
First of all, of the examples in your post, I would rather see the ones with the partial words, they're more informative.

But to answer the question, you could use a regular expression and preg_replace (http://www.php.net/manual/en/function.preg-replace.php), or just look for the last index (strrpos (http://www.php.net/manual/en/function.strrpos.php)) of space.

Whichever you do, I think it would have to be an at least two step operation. First you would shorten the string to 50 characters as you already do, next you would find the spot nearest the end where you want to actually chop it at and add the ...

qwikad.com
10-24-2013, 09:42 PM
This seems to be working great:




<?php

$title = $row['adtitle'];
if (strlen($title) > 50) {
$title = preg_replace('~\s+\S+$~', '', $title);
$title = $title."...";
}
echo $title;

?>



Is that what you had in mind?

traq
10-24-2013, 10:04 PM
That would just chop off the last word, regardless of how long the string is. You'd need to chop it at 50 characters first.


<?php

$title = $row['adtitle'];
if (strlen($title) > 50) {
$title = substr( $title,0,50 );
$title = preg_replace('~\s+\S+$~', '', $title);
$title = $title."...";
}
echo $title;

qwikad.com
10-24-2013, 10:22 PM
that would just chop off the last word, regardless of how long the string is. You'd need to chop it at 50 characters first.


<?php

$title = $row['adtitle'];
if (strlen($title) > 50) {
$title = substr( $title,0,50 );
$title = preg_replace('~\s+\S+$~', '', $title);
$title = $title."...";
}
echo $title;

perfect!