Validate string using regex

Hi Guys!

I have the following regex, but I also want to allow the following characters:

?
*
!
:
"


if(!preg_match('/^[a-z0-9 \\(\\)\\&,_\\/-]{1,100}$/i', $string)) {
			return false;
		} else {
			return true;
		}

How do I modify the code?

Thanks


return (bool)preg_match('~^[a-z0-9 \\(\\)&,_/\\?\\*!:"\\'-]{1,100}$~i', $string);


a-z - match a through z and A through Z (because if the [I]i[/I] modifier)
0-9 - match 0 through 9
\\(  - match ( literally -- needs to be escaped because ( has a special meaning in regex
\\)  - match ( literally -- needs to be escaped because ) has a special meaning in regex
&   - match & literally
,   - match , literally
_   - match _ literally
/   - match / literally
\\?  - match ? literally -- needs to be escaped because ? has a special meaning in regex
\\*  - match * literally -- needs to be escaped because ? has a special meaning in regex
!   - match ! literally
:   - match : literally
"   - match " literally
\\'  - match ' literally - escaped here because the string is delimited with single quotes and the string would end here if we didn't escape it
-   - match - literally - should be escaped in a character set, but since it's at the end of the character set you don't necessarily have to

:wink:

Perfect, thanks! :slight_smile:

None of these comments are true, within a character class.

It should be escaped when in a position that would otherwise denote a character range. This means that it’s okay to not escape at the start/end of the character class and immediately after a character range.

I had the feeling I was missing something … :blush:

Indeed! :slight_smile: