PHP正则表达式特殊字符

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