Scott
Scott

Reputation: 8075

How to match backslash at beginning of line in PHP

After seeing some errors showing up in our apache logs, I've been trying to figure out 'why'. The errors related to a preg_match command where I was trying to find strings that started with a backslash character:

preg_match('/^\\/',$str)

It was reporting "preg_match(): No ending delimiter '/' found"

Out of curiousity I tried double instead of single quotes, and combinations from 1 to 6 backslashes and it always reports the same error. (I ended up switching the test to if(substr($str,0,1) == "\") {} instead for the time being)

Upvotes: 0

Views: 862

Answers (4)

Scott
Scott

Reputation: 8075

OK, weird, I just ran my tests again from scratch and got it working this time with 4 backslashes as I would have expected. My initial thought was the single quotes was still using the first \ to qualify the second. So I tried four but must have screwed something else up in the syntax.

if(preg_match('/^\\\\/', $str)) {}

The above works.

Upvotes: 0

Skatox
Skatox

Reputation: 4284

Because \\ will be escaped as a single \ you'll need to do:

preg_match('/^\\\\/',$str)

Upvotes: 1

Jon
Jon

Reputation: 437386

This is because \\ inside a string literal is translated to a single \ by PHP.

Therefore your regular expression is /^\/, where \ makes the trailing slash be translated literally as a slash and not as the ending delimiter. That leaves the regex without an ending delimiter, so PCRE complains.

The result you would want to have is /^\\/, and to put that inside a string literal you need to double the backslashes, so:

preg_match('/^\\\\/',$str)

That said, if($str[0] === '\\') is much easier to read and faster to execute.

Upvotes: 6

Halcyon
Halcyon

Reputation: 57729

I think this might have to do with ' (single quote)

Try changing them to double quotes ". Two \ should be enough.

Upvotes: -2

Related Questions