0

I'd like to split this string:

Womens Team Ranking Round

in two but only after the second space, for example, it should be like that:

Womens Team

Ranking Round

Thanks for your help.

Kevin
  • 41,329
  • 12
  • 52
  • 68
Charles Dahab
  • 99
  • 2
  • 11
  • 2
    Is your string always 4 words? – Tim Aug 01 '16 at 23:51
  • 3
    As a quick workaround, you can split the string by spaces, concatenate the first two tokens into one string, and concatenate the last two tokens into another string. As @Tim implies above, however, you'd need a guarantee that the string is always 4 words. Otherwise, you can concatenate the first two tokens into one string, and then loop over the rest (after the second space) and concatenate them. – Matt Coats Aug 01 '16 at 23:53

1 Answers1

4

Answering the question as asked, this will give you two strings consisting of the original divided at the second space:

$strings = preg_split ('/ /', 'Womens Team Ranking Round', 3);
$second=array_pop($strings);
$first=implode(" ", $strings);

If you want to split on one or more spaces, use / +/ for the pattern.

You could also do it with a single regex:

$string='Womens Team Ranking Round';
preg_match('/^([^ ]+ +[^ ]+) +(.*)$/', $string, $matches);

This will give you the first two words in $matches[1] and the remainder of the string in $matches[2].

Answering a more complicated question than asked: If you want to break a longer string every two words, then you can remove the last parameter from preg_split and then use array_slice in a loop to re-join the members of the array two at a time.

Answering a question not actually asked at all but possibly the reason for a question like this: Don't forget wordwrap.

Ken
  • 687
  • 7
  • 9