I am looking for fast and good way to add "-" before every word in string. For example "bla bla bla" should become "-bla -bla -bla". I don't want to make an array of this string, then map it, etc. It looks like a wrong and slow way. Do you have any suggestions on this?
Asked
Active
Viewed 4,926 times
5
-
1How do you define word? Is `"42"` a word? What about `"___"`? What about `"-"`? – Mark Byers Nov 21 '11 at 17:27
-
Does it matter if it's slow? How much will that really cost you? Getting a working (if inelegant) solution in place is probably a better use of your time than seeking premature optimization. – Frank Farmer Nov 21 '11 at 17:27
-
by 'making an array of the string' are you referring to the php split() function? That's the way I would approach this – ford Nov 21 '11 at 17:29
3 Answers
10
If we assume that a word is always separated by a whitespace and that the whitespace have no other special meaning we can do:
$str = 'bla bla bla';
$symbol = '-';
$newString = $symbol . str_replace(' ', " $symbol", $str);
echo $newString;
Output:
-bla -bla -bla

Marcus
- 12,296
- 5
- 48
- 66
7
You should use the regular expressions:
echo preg_replace('/(\w+)/', '-$1', 'bla bla bla');
Search online for Perl Compatible Regular Expressions for more details!

Aldo Stracquadanio
- 6,167
- 1
- 23
- 34