开发者

Can't get Regex working in PHP, works in RegEXP program

开发者 https://www.devze.com 2023-04-11 15:26 出处:网络
Here is the input I am searching: \\u003cspan class=\\\"prs\\\">email_address@me.com\\u003c\\/span>

Here is the input I am searching:

\u003cspan class=\"prs\">email_address@me.com\u003c\/span>

Trying to just return email_address@me.com.

My regex class=\\"prs\\">(.*?)\\ returns "class=\"prs\">email_address@me.com\" in RegExp which is OK, I can work with that result.

But I can't get it to work in PHP.

$regex = "/class=\\\"prs\\\">(.*?)\\/";

Gives me an error "No ending delimiter"

Can someo开发者_开发技巧ne please help?


Your original code:

$regex = "/class=\\\"prs\\\">(.*?)\\/";

The reason you get No ending delimiter is that although you are escaping the backslash prior to the closing forward slash, what you have done is escaped it in the context of the PHP string, not in the context of the regex engine.

So the PHP string escaping mechanism does its thing, and by the time the regex engine gets it, it will look like this:

/class=\"prs\">(.*?)\/

This means that the regular expression engine will see the backslash at the end of the expression as escaping the forward slash that you are intending to use to close the expression.

The usual PHP solution to this kind of thing is to switch to using single-quoted string instead of a double-quoted one, but this still won't work, as \\ is an escaped backslash in both single and double quoted strings.

What you need to do is double up the number of backslash characters at the end of your string, so your code needs to look like this:

$regex = "/class=\\\"prs\\\">(.*?)\\\\/";

The way to prove what it's doing is to print the contents of the $regex variable, so you can see what the string will look like to the regex engine. These kinds of errors are actually very hard to spot, but looking at the actual content of the string will help you spot them.

Hope that helps.


If you change to single quotes it should fix it

$regex = '/class=\\\"prs\\\">(.*?)\\/';
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号