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
Possibly Related posts:
- Spliting CSV (comma seperated) entry grouped by double quotes
By using fgetcsv function we can have well formatted output for csv data without any pain. If you don’t want to use fgetcsv function for... - Auto linking text string having image tags using Text Helper in CakePHP
Recently I found that auto linking urls and emails of a string having image tags within was not possible using text helper in CakePHP. It... - Changing “Remember Me” text string in user box in Joomla 1.5
I wanted to change “Remember Me” text in the user login box in Joomla 1.5 to just “Remember” so that it should fit with the... - How to remove meta tag “generator” in Joomla 1.5
On a page that is generated by Joomla, by default you will always see a meta tag like following <meta name="generator" content="Joomla! 1.5 - Open... - Useful string manipulation helpers in CakePHP
CakePHP comes with a bunch of useful helpers and components which provide handy tools for processing and manipulating data. These helpers are not only the...
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.






It works!
Many thanks for sharing this. I am using it for taking keywords directly from a title.
All the best!