Preg_replace with PHP and MySQL, allowing dashes and brackets
I have a website where people can add content and when they type in titles, all characters are filtered when parsing to MySQL with PHP, only allowing members to write text and numb开发者_运维百科ers. But I want to allow dashes (-
) and brackets/parenthesis (()
). Currently, I have:
$video_title = preg_replace('#[^A-za-z0-9 ?!.,]#i', '', $_POST['video_title']);
What shall I add or remove to the preg_replace function to allow these characters?
Just add the \( \) \-
to the expression
[^a-z0-9 ?!.,()-]
Since it just got erased, you only the the a-z
once if it is case insensitive.
This is not really an answer, but it didn't fit well in the comment box.
Note that A-z
may not do what you expect in a regexp character class: it matches all characters whose ASCII code lies between those of A
and z
, which includes all upper- and lowercase letters, but also a bunch of punctuation characters:
echo join("", preg_grep("/[A-z]/", array_map("chr", range(0, 255)))) . "\n";
Outputs:
ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz
精彩评论