Page 1 of 1
Explode Question
Posted: Mon Jul 26, 2004 3:25 am
by bpgillett
hi. i want to add a prefix to each word inputed in a text field. the words are separated by spaces. i can use the explode function to separate the words. but i can't fugure out how to add a the prefix then implode them back into a string. the text input field may have varying numbers of words depending on the user's input. for example:
if $instruments = "perc voice pno" (as inputed by the user)
i want the new string, $instruments = "+perc +voice +pno"
any ideas.
thanks.
?>
Posted: Mon Jul 26, 2004 3:54 am
by CoderGoblin
try the following
Code: Select all
$temp=explode (' ',$your_string);
$your_string='prefix'.implode('prefix',$temp);
The prefix is added to the first word by the 'prefix' before the implode.
Posted: Mon Jul 26, 2004 9:18 am
by bpgillett
thanks codergoblin. that works perfectly!
--brian
implode with suffix
Posted: Mon Jul 26, 2004 2:58 pm
by bpgillett
i appologize for my lack of inference, but i'm now having trouble using this concept to also add a suffix. i tried:
Code: Select all
$temp=explode (' ',$instrumentation);
$n_instrumentation=' +'.implode.'+' (' +',$temp,'+');
Posted: Mon Jul 26, 2004 3:02 pm
by feyd
Code: Select all
$n_instrumentation = ' +' . implode(' +',$temp) . ' +';
trouble adding suffix with implode
Posted: Mon Jul 26, 2004 3:08 pm
by bpgillett
thanks for the suggestion, feyd. it seems, however, to only add the suffix to the last word of the string. i am trying to add the suffix to all words in the string. (the string is a few words separated by spaces.)
the prefix gets added to all words nicely using:
Code: Select all
$temp=explode (' ',$your_string);
$your_string='prefix'.implode('prefix',$temp);
thanks for any more suggestions.
--brian
Posted: Mon Jul 26, 2004 4:03 pm
by feyd
you'll have to walk through the array in order to do that then.
Posted: Mon Jul 26, 2004 4:53 pm
by bpgillett
i'm not sure how to do that. do you mean write a loop that adds the suffix individually to each item in the array? if you could suggest how to code that, i would greatly appreciate it. i've been trying with no success. thanks.
--brian
Posted: Mon Jul 26, 2004 5:16 pm
by bpgillett
i just used a foreach argument and it works. thanks though.
-brian
Posted: Mon Jul 26, 2004 8:00 pm
by feyd
thinking about it, this is a possibility:
Code: Select all
$newstring = 'prefix'.implode('suffix' . ' ' . 'prefix', explode(' ',$oldstring)) . 'suffix';
Posted: Tue Jul 27, 2004 6:08 pm
by bpgillett
wow. that does work. thanks for the help.
-brian