Search code examples
phpregexregex-negationregex-lookaroundsregex-greedy

How to include the single and double quotes in char list?


I wrote the regex expression like this

^[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]+$

Which is checking the the string is symbol only

I use the checker to check that the regex is correct.

Then I put it into my php code

$regex = "^[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]+$";
$regex = '^[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]+$';

Both I tried and its not work because the quote is broken by the quote in the regex.

I don't want to concat them like

$regex="{partA}".'"'."{partB}";

I think this is too difficult to read and not easy to maintenance

How do I solve this problem?


Solution

  • Both of your regexes produce syntax errors in PHP due to there being quotation marks inside of the regex itself.

    If you don't want to concatenate the regex into two different parts, your best approach is to escape the quotation marks with backslashes:

    $regex = "^[-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/]+$";
    $regex = '^[-!$%^&*()_+|~=`{}\[\]:";\'<>?,.\/]+$';
    

    Note that the latter is more preferable, as double quotes will parse any variables stored within the string; if there were any text after the $, and a corresponding variable, the variable's content would be injected into the regex:

    $sample = 'text';
    $regex = "^[-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/]+$sample";
    
    echo $regex;
    // ^[-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/]+text
    

    In addition to this, it's also slightly faster to use single quotes.