preg_quote

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

preg_quote -- Экранирует символы в регулярных выражениях

Описание

string preg_quote ( string str [, string delimiter] )

Функция preg_quote() принимает строку str и добавляет обратный слеш перед каждым служебным символом. Это бывает полезно, если в составлении шаблона участвуют строковые переменные, значение которых в процессе работы скрипта может меняться.

В случае, если дополнительный параметр delimiter указан, он будет также экранироваться. Это удобно для экранирования ограничителя, который используется в PCRE функциях. Наиболее распространенным ограничителем является символ '/'.

В регулярных выражениях служебными считаются следующие символы: . \\ + * ? [ ^ ] $ ( ) { } = ! < > | :

Пример 1. preg_quote() пример

<?php
$keywords
= "$40 for a g3/400";
$keywords = preg_quote($keywords, "/");
echo
$keywords; // возвращает \$40 for a g3\/400
?>

Пример 2. Выделение курсивом слова в тексте

<?php
// В данном примере preg_quote($word) используется, чтобы
// избежать трактовки символа '*' как спец. символа.

$textbody = "This book is *very* difficult to find.";
$word = "*very*";
$textbody = preg_replace ("/" . preg_quote($word) . "/",
                        
"<i>" . $word . "</i>",
                        
$textbody);
?>

Замечание: Эта функция безопасна для обработки данных в двоичной форме.



preg_quote
php dot net at sharpdreams dot com
24-Jul-2005 07:34
Re (2) rdude at fuzzelfish dot com:

In case anyone else missed it, you do NOT have to use / as your preg escape character. You can use any two matching characters.
me@localhost
29-Mar-2005 10:51
Re rdude at fuzzelfish dot com:

You can specify a delimiter that will be escaped, too.
preg_quote('abc/', '/') does the job.
rdude at fuzzelfish dot com
16-Feb-2005 08:35
Another character that preg_quote will not escape is the all important "/" character. You will need to convert "/" into "\/" yourself. For example, this code does not work:

<?
 $TEXT
= preg_replace('/[' . preg_quote('abc/') . ']/', '', $TEXT);
?>

However, this does:

<?
 $TEXT
= preg_replace('/[' . preg_quote('abc') . '\/]/', '', $TEXT);
?>
mina86 at tlen dot pl
25-Dec-2003 03:02
Re: adrian holovaty
You must also escape '#' character. Next thing is that there is more then one whitespace character (a space).. Also IMO the name preg_quote_white() won't tell what the new function does so we could rename it. And finally, we should also add $delimiter:

<?php
function preg_xquote($a, $delimiter = null) {
     if (
$delimiter) {
         return
preg_replace('/[\s#]/', '\\\0', preg_quote($a, substr("$delimiter", 0, 1)));
     } else {
         return
preg_replace('/[\s#]/', '\\\0', preg_quote($a));
     }
}
?>
adrian holovaty
15-Jul-2003 05:12
Note that if you've used the "x" pattern modifier in your regex, you'll want to make sure you escape any whitespace in your string that you *want* the pattern to match.

A simplistic example:

$phrase = 'a test'; // note the space
$textbody = 'this is a test';

// Does not match:
preg_match('/' . preg_quote($phrase) . '$/x', $textbody);

function preg_quote_white($a) {
     $a = preg_quote($a);
     $a = str_replace(' ', '\ ', $a);
     return $a;
}

// Does match:
preg_match('/' . preg_quote_white($phrase) . '$/x', $textbody);

<preg_matchpreg_replace_callback>
 Last updated: Tue, 15 Nov 2005