dtxa49711 2009-10-07 12:53
浏览 19
已采纳

是否有一个PHP函数可以在应用之前逃避正则表达式模式?

Is there a PHP function that can escape regex patterns before they are applied?

I am looking for something along the lines of the C# Regex.Escape() function.

  • 写回答

2条回答 默认 最新

  • dougang7521 2009-10-07 12:55
    关注

    preg_quote() is what you are looking for:

    Description

    string preg_quote ( string $str [, string $delimiter = NULL ] )
    

    preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.

    The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

    Parameters

    str

    The input string.

    delimiter

    If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.

    Importantly, note that if the $delimiter argument is not specified, the delimiter - the character used to enclose your regex, commonly a forward slash (/) - will not be escaped. You will usually want to pass whatever delimiter you are using with your regex as the $delimiter argument.

    Example - using preg_match to find occurrences of a given URL surrounded by whitespace:

    $url = 'http://stackoverflow.com/questions?sort=newest';
    
    // preg_quote escapes the dot, question mark and equals sign in the URL (by
    // default) as well as all the forward slashes (because we pass '/' as the
    // $delimiter argument).
    $escapedUrl = preg_quote($url, '/');
    
    // We enclose our regex in '/' characters here - the same delimiter we passed
    // to preg_quote
    $regex = '/\s' . $escapedUrl . '\s/';
    // $regex is now:  /\shttp\:\/\/stackoverflow\.com\/questions\?sort\=newest\s/
    
    $haystack = "Bla bla http://stackoverflow.com/questions?sort=newest bla bla";
    preg_match($regex, $haystack, $matches);
    
    var_dump($matches);
    // array(1) {
    //   [0]=>
    //   string(48) " http://stackoverflow.com/questions?sort=newest "
    // }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?