preg_quote

  • When we use a string as a regular expression, we want to escape the characters that could be interpreted as regexp special characters. PHP does this using preg_quote, and Ruby has an equivalent Regexp.escape method.

    In this example, we’ll escape any regular expression special character in the given string.

    PHP

    $string = '[my_file.gif]';
    $result = preg_quote($string);
     
    var_export($result);
    // => '\\[my_file\\.gif\\]'

    Ruby

    string = '[my_file.gif]'
    result = Regexp.escape(string)
     
    p result
    # => "\\[my_file\\.gif\\]"

Looking for Rails or PHP web application development, integration, and training?

Rails for PHP is brought to you by Maintainable Software. Get custom web applications and personalized training from the authors of the book and website.