Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

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_replace_callback> <preg_match
Last updated: Sat, 27 Jan 2007
 
add a note 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 :)
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_replace_callback> <preg_match
Last updated: Sat, 27 Jan 2007
 
 
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571