Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add some symbol to every word in string?

Tags:

php

php-5.3

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?

like image 820
VitalyP Avatar asked Nov 21 '11 17:11

VitalyP


3 Answers

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
like image 127
Marcus Avatar answered Oct 15 '22 16:10

Marcus


You should use the regular expressions:

echo preg_replace('/(\w+)/', '-$1', 'bla bla bla');

Search online for Perl Compatible Regular Expressions for more details!

like image 24
Aldo Stracquadanio Avatar answered Oct 15 '22 16:10

Aldo Stracquadanio


How about

preg_replace('/(\w+)/i', '-$1', $string);
like image 34
Cyclonecode Avatar answered Oct 15 '22 14:10

Cyclonecode