5

I have a text like this:

line 1/1/1/2

The text after the line phrase is the parameter of a function, for example when I call extractData('1/1/1/2' , 'The main text'):

function extractData($line, $text)
{
    $pattern = "/line(\s+)$line/";
    if(preg_match($pattern, $text)) {
        // some code
    }

}

How can I escape the slash character in the pattern? In other words, how should I write the pattern? ($pattern = "/line(\s+)$line/";)

3 Answers3

12

You can use preg_quote function:

$pattern = '/line(\s+)' . preg_quote($line, '/') . '/';
hsz
  • 148,279
  • 62
  • 259
  • 315
5

To scape any character you use \, so to escape / you use \/

If you want to escape \, you need to escape it as \\\

5

\Q and \E can be used to ignore regular expression metacharacters in the pattern as well.

$pattern = '~line(\s+)\Q' . $line . '\E~';
hwnd
  • 69,796
  • 4
  • 95
  • 132
  • That's good to know! Still something new here :) Didn't find much [documentation](http://perldoc.perl.org/perlre.html) about it, but seems [to work](http://regex101.com/r/pI4xW2/1). – Jonny 5 Aug 12 '14 at 12:51
  • 1
    @Jonny5 [perldoc](http://perldoc.perl.org/functions/quotemeta.html), [regex-info](http://www.regular-expressions.info/characters.html) – hwnd Aug 12 '14 at 13:45