5

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?

j0k
  • 22,600
  • 28
  • 79
  • 90
VitalyP
  • 1,867
  • 6
  • 22
  • 31
  • 1
    How 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 Answers3

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
3

How about

preg_replace('/(\w+)/i', '-$1', $string);
Cyclonecode
  • 29,115
  • 11
  • 72
  • 93