0

I am trying to read some php code and was wondering why preg_replace always has the slashes. In the regex's I've written in C++, I don't do the same thing and was wondering why

PHP: preg_replace('/blah/', '', $str) but in C++ I'd make a regex with just the string "blah"

Can I get some clarification here? What are the start and end slashes for? Thanks

2 Answers 2

6

They are just regex delimiters. From the PHP manual documentation on Delimiters:

A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

Often used delimiters are forward slashes (/), hash signs (#) and tildes (~). The following are all examples of valid delimited patterns.

1
  • 2
    as the manual says.. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character. so it is possible. ^.^ May 3, 2013 at 21:46
3

They're delimiters, allowing you to add modifiers, e.g. /blah/i for a case insensitive regex.

The use of slashes comes from perl or shell/sed insofar as I'm aware.

In php, they're not mandatory, in the sense that you can use other characters. For instance, "!blah!i" works too. There also is a special syntax with brackets, which is much less error prone since you don't need to escape it: "{blah}i".

2
  • so, is this the same for C++ regex's as well?
    – jamesatha
    May 3, 2013 at 21:36
  • I'm not sure which flavor the C++ regex use. They're the same as Perl, since the preg_* functions stand for Perl-compatible. May 3, 2013 at 21:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.