-1

This is my code

$keywords = mysql_escape_string(preg_replace("/[^ \w]+/", '',($_POST['keywords'])));

and this my output

sample products products sample

Here I don't want to replace comma also.

The input is

sample products!@, products#$#, sample
1
  • 4
    You mean like "/[^ \w,]+/".... is this really rocket science?
    – Mark Baker
    Commented Mar 3, 2014 at 12:16

2 Answers 2

2

If you don't want to get rid of ,s, you can add them to your group in the square brackets:

preg_replace("/[^, \w]+/", '',($_POST['keywords']))
0
1

try this

$keywords = preg_replace("/[^A-Z, ]/i", '',($_POST['keywords']));
echo $keywords;

Demo

Note: this replaces the content which does not match with the regex. Here it replaces anything except alpabets(case in-sensitive ) and comma , and blank space

3
  • 3
    This would change what is qualified as a match since \w also matches underscores.
    – Anonymous
    Commented Mar 3, 2014 at 12:25
  • 1
    yes correct , based on assumption he need only alphabets and , i have written this regex
    – krishna
    Commented Mar 3, 2014 at 12:27
  • Still, he/she may need them to be included for one reason or another so you should at least warn the op that the matches may be different.
    – Anonymous
    Commented Mar 3, 2014 at 12:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.