I have a web form that does a search replace function.
The form input is passed through preg_quote. That's been fine, until now.
Now I want to allow users to input the * (asterisk) wildcard character. preg_quote escapes it. How can I allow it through and properly apply it?
$find = ',*'; // I want to match a comma and all characters after the comma
$replace = ''; // replace with empty string
$find = preg_quote($find_replace[0],'~'); // $find == ',\*';. I want * to remain unescaped. Is replacing "\*" with "*" the best way?
if(strpos($find,'\\*') !== false) { // UPDATE: I tried that, and it does work.
// $find == ',\*'
$find = str_replace('\\*','*',$find);
// $find == ',*' -- seems like it should work but doesn't
}
$value = trim(preg_replace('~' . $find . '~i',$replace,$value));
EDIT:
I added in code above that strips out the escaping slash before the *. It is working.
With $value = 'Hey, hey, hey, hey' I end up with 'Hey hey hey hey'.
All the commas are removed, as expected with the regex pattern ,* (greedy matching?).
Note, in my code I'll be using $find = str_replace('\\*','.*',$find) or $find = str_replace('\\*','[\s\S]*',$find)to replicate Microsoft Excel Find/Replace functionality.