Jump to content

limiting the string length by the number of words


etrader

Recommended Posts

This might be a crude way of doing it, but I'll suggest it anyways.

 

<?php
$string = 'word1-word2-word3-word4-word5-word-6-word7';
$count = explode('-',$string);
$newstring = '';
for($x=0;$x<5;$x++):
$newstring .= '-'.$count[$x];
endfor;
$newstring = substr($newstring,1);
echo "$string<br />$newstring";
?>

 

Edit: I messed up first time around with the code.

You can also use regular expressions.  This way would also be a bit more dynamic if you ever want to change requirements:

$subject = "word1-word2-word3-word4-word5-word6-word7";
$pattern = "/(\w*-){5}/i";
preg_match($pattern, $subject, $matches);
echo $matches[0];
?>

 

<?php
$string = 'word1-word2-word3-word4-word5-word-6-word7';
$count = explode('-',$string);
$newstring = '';
for($x=0;$x<5;$x++):
$newstring .= '-'.$count[$x];
endfor;
$newstring = substr($newstring,1);
echo "$string<br />$newstring";
?>

 

When the number of words is lesser than the limit defined, it adds "-"s at the end of the string.

$subject = "word1-word2-word3-word4-word5-word6-word7";
$pattern = "/(\w*-){5}/i";
preg_match($pattern, $subject, $matches);
echo $matches[0];
?>

 

As I tried, this returns nothing.

 

Works fine for me.  Did you implement this with other code?

 

Also, to get rid of the last dash, change the regex pattern to:

$pattern = "/(\w*-){4}\w*/i";

If it doesn't match print out the original text or whatever you please:

$subject = "word1-word2-word3";
$pattern = "/(\w*-){4}\w*/i";
if(preg_match($pattern, $subject, $matches))
{
   echo $matches[0];
}
else
{
   echo $subject;
}
?>

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.