当前位置: 动力学知识库 > 问答 > 编程问答 >

regex - Differences in backslashing between Notepad++ and PHP

问题描述:

EDIT: I found a solution I didn't expect. See below.

Using regex via PHP's preg_match_all , I want to match a certain url (EDIT: that is already escaped) in a string formatted as json. The search works wonderfully in Notepad++ (using regex-matching, of course) but preg_match_all() just returns an empty array.

Testing on tryphpregex.com I found out that somehow my usual approach to escaping a backslash gives a pattern error, i.e. even the simple pattern https:\\ returns an empty result.

I'm utterly confused and have been trying to debug for too long so I may miss the obvious. Maybe one of you can see the simple error?

The string.

The pattern (that works fine in Notepad++, but not in PHP):

%(https:\\/\\/play.spotify.com\\/track\\/)(.*?)(\")%

网友答案:

You don't need to escape the slash in PHP %(https://play.spotify.com/track/)(.*?)(\")%

The Backslash before doule quote is only needed if you enclosures are double quotes too.

网友答案:

Found a solution to my problem.

According to this site, I need to match every backslash with \\\\. Horrible, but true.

So my pattern becomes:

$pattern = "%(https:\\\\/\\\\/play\.spotify\.com\\\\/track\\\\/)(.*?)(\")%";

Please observe that I tried to find a pattern inside a string that didn't contain clear urls, but urls containing escape characters (it was a json-output from spotify)

分享给朋友:
您可能感兴趣的文章:
随机阅读: