The string I am trying to split is $item[\'category_names\'] which for example contains Hair, Fashion, News
I currently have the following
The error in your code is this:
$categories = "" . $cat . " \n";
You are overwriting $categories at each iteration, it should be:
$categories .= "" . $cat . " \n";
Not sure if I am going the right way about this?
find and replace isn't what explode is for. If you just want to correct the code error - see above.
This is more efficient:
$categories = "" .
str_replace(', ', " \n", $input) .
" \n";
And this also accounts for variable whitespace:
$categories = "" .
preg_replace('@\s*,\s*@', " \n", $input) .
" \n";