There is the following function:

$currentURI = rtrim($_SERVER['REQUEST_URI'], '/') . '/'; $currentURI = preg_replace('~page=[0-9]+~', '', $currentURI); 

Question: how to write the following regular expression correctly:

 $currentURI = preg_replace('~/?page=[0-9]+~', '', $currentURI); 

Where /? - the content of the string, not the regular expression syntax? How to do it right?

  • 2
    backslash \ / \? - Jean-Claude

3 answers 3

You can escape characters in regular expressions with a backslash: ~/\?page=[0-9]+~ . Thus, these characters will be perceived as the most ordinary characters, not special characters.

  • one
    inside ~ possible and / \? - Jean-Claude
  • @ Jean-Claude, thanks, corrected the answer. - neluzhin

You can use preg_quote to escape special characters in reg expressions.

 $str = preg_quote("/?page=", '~'); // '/\?page=' $currentURI = preg_replace("~{$str}\d+~", '', $currentURI); 

In your case, it probably makes sense to more specifically describe what you need.
For example:

 $currentURI = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); 
  • using preg_quote () makes sense for dynamic patterns. For shielding one or two characters, this function can also be used, but does it make sense to shoot from a cannon on sparrows? - Edward
  • First, why not, and secondly, this is just an alternative answer. The answer about the backslash was already. - vp_arth

As an alternative answer, you can add that in PCRE regular expressions (i.e. in PHP) and Perl, a special sequence \ Q ... \ E is supported, inside which all metacharacters are ignored (of course, except for the closing \ E) .

In addition, it is still possible to convert metacharacters into literals (that is, into plain text) using the character class [...] , but in this case there are a couple of exceptions.

First, the cover character ^ , written immediately after the opening square bracket of the character class [^ , will remain a metacharacter, which means inverting the character sequence of the current character class. If you want to use the cover as a literal, it is enough to write it in any other position (but not in the first) . For example, this pattern '~ [? ^] ~' Will match the characters ? or ^ , but will this '~ [^?] ~' match any single character except the character ? .

Secondly, the dash - character written between character class literals will not match the dash character. To convert a dash from a metacharacter to a literal, you need to write it at the beginning or at the end of a character class. For example, the entry '~ [- ^?] ~' Will correspond to one of the three characters in this position: a dash, a cover, or a question mark.

As for the forward slash / - it does not belong to the group of metacharacters, and it only requires shielding if it is the delimiter of the regular expression pattern. But in such cases it is more convenient to replace the delimiter symbol with any other one suitable for the current template.