-4

I have this string in php

 $string="lorem-ipsum-dolor-sit-amet-consectetur-adipiscing-elit-sed-do-eiusmod-tempor-incididunt-ut-labore-et-dolore-magna-aliqua";

I want to retrive just the six first words between -, in this case

  function retrieve6firstWords($string){


    return $string;
    }

 echo retrieve6firstWords($string); //$string= "lorem-ipsum-dolor-sit-amet-consectetur";

How can I do this?

joe
  • 1
  • 1
  • your link gets the string from a sentence. In this case it comes from a friendly url...Can you makr it as duplicate with some other question like this? – joe Aug 03 '18 at 19:40
  • The source of the string does not matter. You can very easily alter the other solution to fit your needs especially since you just plan to implement a `retrieve6firstWords()` function. – MonkeyZeus Aug 03 '18 at 19:42

1 Answers1

0

explode by -, slice the array to only 6 and implode back into a string.

<?php
$string = "lorem-ipsum-dolor-sit-amet-consectetur-adipiscing-elit-sed-do-eiusmod-tempor-incididunt-ut-labore-et-dolore-magna-aliqua";

$words = explode('-', $string);

$words = array_slice($words, 0, 6);

$string = implode('-', $words);

print_r($string);

Result:

lorem-ipsum-dolor-sit-amet-consectetur

https://3v4l.org/YtVrE

If you want the words and not a string they are in the array, just don't implode it.

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106