0

I asked recently a question and received very nice answers to solve my newbie doubts. Based on them and tips/tricks from several websites, I've been trying to get solved the following doubt but without success. Basically, I'd like to explode sentences (with variable number of words) and then implode it but with a certain pattern.

For instance:

input: coastal basin dr54 dr34 valley
output: this is @ word(coastal) or this is @ word(basin) or this is @ word(dr54) or this is @ word(dr34) or this is @ word(valley)

so, basically to add this is @ word() for each word and then separate them with or. In case the sentence has only one word (e.g., coastal), it should not appear or (ie., this is @ word(coastal)).

I explode the input as below but had no success to implode it as I want it:

php > $sentence = 'coastal basin dr54 dr34 valley';
php > print_r($sentence);
coastal basin dr54 dr34 valley
php > $words = explode(' ', $sentence);
php > print_r($words);
Array
(
    [0] => coastal
    [1] => basin
    [2] => dr54
    [3] => dr34
    [4] => valley
)

Not sure if this is too simple, but if it is, please bear with me! I'm pretty new in php. Any hint is welcomed,

Community
  • 1
  • 1
Gery
  • 8,390
  • 3
  • 22
  • 39
  • 2
    `$result = implode(' or ', array_map(function ($value) { return 'this is @ word('.$value.')'; }, $words)` – Mark Baker Oct 28 '14 at 11:58
  • 1
    `$words = explode(' ', $sentence); $sentence1 = 'this is @ word(' . implode(') or this is @ word(', $words) . ')';` – k.tarkin Oct 28 '14 at 12:00
  • @MarkBaker Mark Mark Mark Mark!! again my friend, genius! thanks a lot! if you put it as answer I'll mark it as such – Gery Oct 28 '14 at 12:08
  • @MarkBaker if I try to put single quotes wraping `'.$value.'` it gives an error `PHP Parse error: syntax error, unexpected ''.$value.'' (T_CONSTANT_ENCAPSED_STRING) in php shell code on line 1`, is there a way to do that? ie. `this is @ word('coastal')` – Gery Oct 28 '14 at 14:34
  • @MarkBaker I found it, `\'` – Gery Oct 28 '14 at 14:50
  • You shouldn't be wrapping `'.$value.'` in quotes, you should be wrapping `'this is @ word('` and `')'` in quotes.... those are your string literals – Mark Baker Oct 28 '14 at 14:50
  • @MarkBaker this works: `$result = implode(' or ', array_map(function ($value) { return 'this is @ word(\''.$value.'\')'; }, $words));`, is it right? – Gery Oct 28 '14 at 15:28
  • No, it isn't right..... the code that I originally posted is right - [demo](http://ideone.com/mkAbfo) – Mark Baker Oct 28 '14 at 15:42
  • that one doesn't work if I want `this is @ word('coastal')` – Gery Oct 28 '14 at 16:41

0 Answers0