Jump to content

how to remove first 3 words on a string


ccherry17

Recommended Posts

Hello again to all

 

I would like to ask if how can i removed the first 3 words on this string?

 

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque hendrerit accumsan turpis, vitae rutrum quam cursus id. Sed quis pulvinar eros. Integer vel tellus turpis. Donec tortor dolor, convallis in mollis et, rhoncus eu lacus. Etiam quam risus, fringilla ac tempor in, congue vel felis. Mauris eu luctus augue. Fusce nisl neque, convallis a posuere a, ultricies et metus.

 

thanks in advance :)

Link to comment
https://forums.phpfreaks.com/topic/256663-how-to-remove-first-3-words-on-a-string/
Share on other sites

You should look at the PHP function explode, here's a little example I made.

 

<?PHP

  $string = 'mine +440983234213 adam look at this sentence, first 3 words are removed! <br>';
  
  echo $string;
  
  $explode_str = explode(' ', $string, 4);
  $string = $explode_str[3];
  
  echo $string;
  
?>

 

Try that out and see how it goes, remember to have a little read up on the function too.

 

Regards, PaulRyan.

The most efficient way of doing this would be to use a series of strpos calls. The first would need to find the first occurrence of a space from the start of the string; the second would need to find the next occurrence from after the point where the first was found; and then the third call would need to find the next occurrence from after the point where the second was found. Once you know the position of the third space, you can use substr to select the text after that point:

 

$str = 'one two three four';

$pos1 = strpos($str, ' ');
$pos2 = strpos($str, ' ', $pos1+1);
$pos3 = strpos($str, ' ', $pos2+1);

if ($pos3 !== false) {
    $str = substr($str, $pos3+1);
}

 

Using explode() will create a potentially large array when it's not necessary - much faster to seek through the string to find the positions.

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.