My requirement is to remove all special symbols except underscore from a string.
I am using..
$string = 'text-text_text+text@text(text)text&text.text*text\text/text';
$columnName = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '_', $string);
Output:
text-text_text_text_text(text)text&text.text_text_text_text
But its not removing periods, ampersand, brackets and dash. I felt like helpless while creating this regular expression. Please help..
When you want to remove all chars except letters, numbers and underscore simply use
preg_replace('/[^a-zA-Z0-9]/', '_', $string);An expression like
[^...inPREGfunction means, that you want to keep all following chars (so your expression results in not(!) removing ampersands, brackets a.s.o.BTW: I ommit the underscore in the expression, because it would be replaced by a underscore again, so no need to list it in the regex