$count = preg_match_all("#\[tag\](.*?)\[/tag\]#si", $text, $match, PREG_PATTERN_ORDER); for ($i=0; $i<$count; $i++) { $listitems = explode(",", mb_strtolower(str_replace(array(", ", ", "), ",",trim($match[1][$i])))); $listtext = ""; foreach($listitems as $item) { $item = trim($item); if(!empty($item)) { $listtext .= "".$item.", "; } } $text = str_replace($match[0][$i], $listtext, $text); } unset($count); unset($listitems); unset($listtext); unset($match);