Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php regex escaping special characters [duplicate]

Tags:

regex

php

I wrote the following code (yes it does work) and was wondering why I don't need to escape the '<' and '>' characters inside the pattern since they are considered 'special' characters by the php manual.

http://www.php.net/manual/en/function.preg-quote.php

var_dump(preg_match('/<[A-Za-z][A-Za-z0-9]*>/', "<html>", $matches));

echo "<pre>";
var_dump(htmlentities($matches[0]));
echo "</pre>";

output:

int(1) 
string(12) "<html>"
like image 278
Robert Rocha Avatar asked Mar 10 '13 00:03

Robert Rocha


People also ask

How do you escape special characters in regex?

The \ is known as the escape code, which restore the original literal meaning of the following character. Similarly, * , + , ? (occurrence indicators), ^ , $ (position anchors) have special meaning in regex. You need to use an escape code to match with these characters.

What is escaping special characters in PHP?

An escape sequence tells the program to stop the normal operating procedure and evaluate the following characters differently. In PHP, an escape sequence starts with a backslash \ . Escape sequences apply to double-quoted strings. A single-quoted string only uses the escape sequences for a single quote or a backslash.

How do you bypass special characters?

Use braces to escape a string of characters or symbols. Everything within a set of braces in considered part of the escape sequence. When you use braces to escape a single character, the escaped character becomes a separate token in the query. Use the backslash character to escape a single character or symbol.

What is escaping in regex?

The backslash in a regular expression precedes a literal character. You also escape certain letters that represent common character classes, such as \w for a word character or \s for a space.


1 Answers

Only the characters listed on this page need to be escaped in PHP regex matching/replacing.

While < and > can act as delimiter, it doesn't need to be escaped in the given example because you already have /(slash) acting as a delimiter.

Referring to the link in question

The preg_quote() function may be used to escape a string for injection into a pattern and its optional second parameter may be used to specify the delimiter to be escaped.

like image 60
hjpotter92 Avatar answered Oct 27 '22 01:10

hjpotter92