简体   繁体   中英

PHP Regular Expression special characters

I am facing difficulties to validate the below format. I want regular expression needs to be satisfied with the below condition.

$pattern = '/^\w[\w\s\.\%\-\(\)\[\]]*$/u';
$file_name = "(00)filename.jpg";
if(preg_match($pattern,$file_name)){
    echo "Pattern matched";
}else {
    echo "Pattern not matched";
}

I have tried several ways. But, the main problem is do not write the own pregmatch, instead need to modify the existing one which accepts the brackets().

So this should match (00)filename.jpg and does not, because your regex requires the string to ^\\w start with a word-character. You can add optional parenthesized \\w+ to the start:

^(?:\(\w+\)|\w)[-\w\s.%()[\]]*$

Also need to put the hyphen - at the start or end inside the character class. Else it would express a range. Furthermore need to escape the closing ] inside the character class.

test at regex101


But possibly, you just want to check:

  • if there's at least one word-character in the string.
  • the string consist only of [-\\w\\s.%()[\\]]

If so, use a lookahead to check for the \\w :

^(?=.*?\w)[-\w\s.%()[\]]+$

test at regex101

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