Jump to content

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.

As I said, it was crude... But surely you can work with it? Or are you expecting other people to do most of the work for you?

 

No, I can replace "-"s by means of str_replace; but I am not sure if it is the simplest way to do so.

$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;
}
?>

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.