0

For instance, in one case the sentence can have 2 words, and in other case the sentence can have 5 words. I think that I can use explode to get every word in each case (something like here), the problem is that the number of words in each sentence varies. After that initial problem, I need to resemble the sentence but using & instead of blank spaces, e.g.,

input:   this is a sentence
output:  this & is & a & sentence

I'm new in php, so please bear with me if this question is very simple.

Thanks in advance for any hints!

Community
  • 1
  • 1
Gery
  • 7,746
  • 3
  • 20
  • 37
  • 2
    `$result = implode(' & ', str_word_count($original,2));` – Mark Baker Oct 27 '14 at 18:58
  • @MarkBaker thanks for that nice line command. One question about it, I know that in awk I can use `awk '{ if ( x < 2) print $0 }' file` to use a simple if call. Is it possible to do something similar in your command? the thing is that I want to leave the sentence if it has only one word, and apply your line command if it has 2 or more words, thanks for any further suggestions. – Gery Oct 27 '14 at 20:22
  • 1
    Not testing for the word count as part of a clean one-liner; but if you only have one word in the sentence, then you'll only have one word in the end result without any ampersand – Mark Baker Oct 27 '14 at 20:26
  • @MarkBaker just tested it and you're right, it gives the same input, cool answer, thanks for that. – Gery Oct 27 '14 at 20:46

2 Answers2

1

Use explode -

$sentence = "this is a sentence";
$words = explode(' ', $sentence);
print_r($words);

And then implode -

$updated = implode(" & ", $words);
echo $updated;

This method does not care how many words are in the sentence, so it can be used with any sentence.

Jay Blanchard
  • 33,530
  • 16
  • 73
  • 113
1

Use explode to split the words by space. Then use implode to put them back together with the & between the words.

$string = 'this is a sentence';
$words = explode(' ', $string);
$newstring = implode(' & ', $words);
var_dump($newstring);

Or you can use str_replace to replace all spaces with the &.

$string = 'this is a sentence';
$newstring = str_replace(' ', ' & ', $string);
slapyo
  • 2,984
  • 1
  • 14
  • 23