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?
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
You should use the regular expressions:
echo preg_replace('/(\w+)/', '-$1', 'bla bla bla');
Search online for Perl Compatible Regular Expressions for more details!
How about
preg_replace('/(\w+)/i', '-$1', $string);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With