Converting a text string into comma separated words

Today, i was looking at some old code of mine to find something when i found this little but useful piece of code which i had written for one of my old projects (and of course when i didn’t had this blog created yet). The idea was to create comma separated words from a string, something like, creating meta keywords from a piece of information (such as meta description).

For example, suppose, we have a string A Quick brown fox jumps over the lazy dog which we would pass to a function using this code. As a result we would have A, Quick, brown, fox, jumps, over, the, lazy, dog. Moreover, it removes everything except alphanumeric to have more cleaner string. If you are looking for a pure string cleaner built using php [go here]

Here is the function:


function convert_to_csv($string) {
$patterns = array("/[-]/","/[^\w\s]/");
$replacements = array(" ","");
$string = urldecode($string);
$string = preg_replace($patterns,$replacements,$string);
$string = preg_replace("/(\s){2,}/"," ",$string);
$string = preg_replace("/\s/",", ",$string);
$string = preg_replace("/^,/","",$string);
return $string;
}

Isn’t it useful :)

One thought on “Converting a text string into comma separated words

Leave a Reply