Hi, There are two types of strings: 1) AAA BBB CCC - DDD &(&) FFF 2) AAA BBB CCC - DDD How can I create a pattern in preg_replace to achieve the following: AAA-BBB-CCC-DDD-FFF or AAA-BBB-CCC-DDD I tried the following but not familiar with the syntax: $patterns[0] = ' '; //white space $patterns[1] = ' '.'-'.' ';//white space + '-' + white space $patterns[2] = ' '. '&'. ' ';//white space + & + white space $replacements[0] = '-';//replace white space with dash $replacements[1] = '-';//space - dash - space with dash $replacements[2] = '-';//space - & - space with dash echo preg_replace($patterns, $replacements, $string); PHP: I need a general pattern to get rid of "&" (if there is) and white spaces Thanks
Hmm.. I'm not too good at regexp but maybe this will work: preg_replace('/[^a-z0-9]/i','-',$string); //it should replace all characters which aren't a-z or 0-9 with "-" Let me know if it works It would need to be changed to get rid of specific things ( & ) but its a general way to get rid of &+white space
Hi, Thanks for the reply, I tried this but it gives: AAA-BBB-CCC---DDD-&-FFF $title = preg_replace("/(&| |[\s])*$/i", '', str_replace( ' ', '-', $title )); PHP: The worst case I would not mind & but triple dashes (---) do not seem good.
$title = preg_replace('/&/', '-', $string); $title = preg_replace('/[^a-z0-9]+/i', '-', $title); Code (markup):
Thanks for the reply Aboyd, it worked! So the trick is using [^a-z0-9]+ which replaces triple dashes into one. (+) Is that correct?