views:

76

answers:

2

Need a little help with string formatting...

I have a string like this:

Bmw m3 fully equipped and low mileage

I need to replace whitespaces with commas, and also at the same time remove all special characters (all non number non letter characters except swedish å ä ö)

Then I need to remove all but the first 5 words, or you could say everything behind the fifth comma sign.

I want something like this from the string above:

Bmw,m3,fully,equipped,and

Thanks

+1  A: 

mhmmm try this:

$string = "Bmw m3 fully equipped and low mileage";
$str = implode(',', explode(' ',$string,5));
echo substr($str,0,strpos($str, ' '));

not tested though....

someGuy
Tested, works fine :) well, except for removing special characters, and it won't handle multiple whitespaces.
no
ah dammit... i should read the question properly _D
someGuy
+2  A: 

(Result)

$res = preg_replace('/[^a-z0-9åäö\s]/ui', '', $theString);
$arr = preg_split('/\s+/', $res, 6);
echo implode(',', array_slice($arr, 0, 5));

This assumes you want to join multiple consecutive spaces (e.g. foo    bar) together (foo,bar).

KennyTM