PHP: preg_quote - Manual

downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

preg_replace_callback preg_match

Last updated: Sat, 27 Jan 2007

view this page in

# 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);
?>`

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

add a note User Contributed Notes
preg_quote
chad
04-Dec-2006 02:03
`If you are placing your quoted string within []'s, make sure you also escape the dash (-) character manually.
preg_match("/^[A-Za-z\d" . preg_quote('!@#$%^&*()-_=+\|[]{};:/?.><', '/') . "]{8,32}$/", $password)
The above will try to match the characters ')' through '_' whatever those are. So use the below expression:
preg_match("/^[A-Za-z\d" . preg_quote('!@#$%^&*()_=+\|[]{};:/?.><', '/') . "\-]{8,32}$/", $password)
Yes, I know I can use \w in place of A-Za-z, but I wanted to illustrate my point better :)`
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);`
add a note
preg_replace_callback preg_match

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 10:36:09 2007 PST