简体   繁体   中英

Regex expression to allow an apostrophe

I've been looking at all of the other posts regarding this topic but I'm still unable to get my regex expression to allow an apostrophe. I thought the following should work but it keeps giving an error. It does allow all of the other characters, numbers and letters, just not the ' (I need it for words like Mike's )

/^([-a-zA-Z\/\-\&\\\?\!\,\.\'\"\s0-9@:=_]{1,1000})$/

The regex expression is required for validation of a form and part of the following:

public $regex = array ('char' => "/^[a-zA-Z.\s]{0,50}$/", 
                       'misc' => "/^([-a-zA-Z\/\-\&\\\?\!\,\.\'\"\s0-9@:=_]{1,1000})$/");

if(preg_match($this->regex[$validation],$this->filteredValue[$fieldName])) { 
    $this->messageArray[$fieldName] = '<span class="cheers"> &nbsp; Thank You</span>';   
}

Can anybody tell me where I am going wrong please?

The \\' should work. I can't say why it does not. I can, however, offer a workaround. You can try to replace the ' with a hex representation of the same character. instead of using \\' try to use \\x1b .

Also, you should move the \\- to be just a - at the end of the []

/^([-a-zA-Z\/\&\\\?\!\,\.\x1b\"\s0-9@:=_-]{1,1000})$/

And I don't understand what's the - at the beginning is...


EDIT: After seeing your last comment regarding the error that you get I can only assume that you have mis-identified the problem that you have. For what I see assume that your regexp is all fine, but you have a problem in your SQL statment as you have not escaped the data.

You should familiraize yourself with mysql_real_escape_string and make sure you use it in all your queries. For Example:

<?php
// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
            mysql_real_escape_string($user),
            mysql_real_escape_string($password));
mysql_query($query);

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM