dtq26360 2019-05-22 04:18
浏览 126
已采纳

如何在char列表中包含单引号和双引号? [重复]

This question already has an answer here:

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?

</div>
  • 写回答

3条回答 默认 最新

  • dongzhenyin2001 2019-05-22 04:21
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?