PDA

View Full Version : Page title length and repeating words


bentleybloke
05-Sep-2008, 05:02 PM
Afternoon all, I've been playing around with the AUG php for marketing lists that limits the number of words. I've added a line to stop the words being repeated for use to generate a page title, but have a problem if the word original word count is less than the defined cut off.

$sShort = "";
$nCount = 0;
$sOriginal = "some string";
foreach(explode(" ", $sOriginal) as $sWord)
{
if ($nCount > 12)
{
$sShort .= "...";
break;
}
if (strpos($sShort, $sWord) !== false) continue;
$sShort .= $sWord . " ";
}
echo $sShort;

If $sOrigininal has fewer than the 12 words defined in $nCount, then I get the error:

Warning: strpos(): Empty delimiter. in main on line 12

I whole heartedly admit that I know nothing about php and would be grateful if someone would tell me where I've gone wrong.

acompton
08-Sep-2008, 04:21 PM
I'm confused. Is $nCount meant to be count of the number of words added so far? If so, then it isn't going to work because you don't increment it.

The error shows that you're getting an empty value in $sWord, which is surprising. The foreach should only be giving you the individual words.

I would avoid the error and tidy up the if like this:

if ((strlen($sWord) > 0) && (strpos($sShort, $sWord) === false))
$sShort .= $sWord . " ";


I'm not a PHP expert.

gabrielcrowe
09-Sep-2008, 01:27 PM
This code is overly complicated and prone to error, try this function as a better example:

#GC: shorten to words
if (!function_exists('ShortenByWords')) {
function ShortenByWords($string='', $chars=20, $elli='...'){
list($new_string, $elli)= explode("\n", wordwrap($string, $chars, "\n", false));
return ( $elli ) ? $new_string.'...' : $new_string;
}
}

$sShort = "...";
$nCount = 50;
$sOriginal = "some string";

echo ShortenByWords($sOriginal,$nCount,$sShort);

bentleybloke
09-Sep-2008, 02:23 PM
Thanks guys, will have a go and post back.