Lizard
Lizard

Reputation: 44992

regex encapsulation php

What are the differences pros/cons of using either '/' or '#' as the regex encapsulation

e.g.

'/' = preg_match('/MYSEARCH}(.+)ENDMYSEARCH/s',$out,$matches);

'#' = preg_match('#MYSEARCH}(.+)ENDMYSEARCH#s',$out,$matches);

Thanks!

Upvotes: 2

Views: 370

Answers (2)

OIS
OIS

Reputation: 10033

Also remember that with preg_quote you can add the delimiter to be escaped.

Upvotes: 1

Pascal MARTIN
Pascal MARTIN

Reputation: 400952

The only thing that matters to PHP / PCRE is that you must use the same character at the beginning and at the end.

What matters to you is escaping : inside the regex, you have to escape the delimiter if you want to use it.

For instance, to match a part of an URL, using / as a delimiter, you regex might look like this :

'/^http:\/\/www/'

Using / as delimiter, you have to escape the slashes which are inside the regex -- not easy, and not looking well.

On the other hand, using # as delimiter :

'#http://www#'

Much more easier to write and read, isn't it ?


Depeding on your need and/or preference, you can use whatever character you want -- I sometimes see '!' or '~', for instance.

Upvotes: 7

Related Questions