开发者

PHP regex multi-line

I have the following PHP regex

preg_match('/[\/\/\*] First: (.*)\n[\/\/\*] Second: (.*)\n/i', $some_string)

but for some reason it will not match this text:

// First: a string
// Second: another string

I tried changing line endings between Windows and Unix style, this did nothing. I also tried splitting up the regex to match Fir开发者_如何学JAVAst and Second separately; this worked but when I put them both together they no longer match the sample text. It seems to have something to do with the space after the second [\/\/\*].. any ideas?

Note I can't change the regex; this is client code that I reversed because they don't provide documentation. This code looks for certain pattern in PHP files in order to load them as 'plugins' in their product. Really I'm trying to guess what header I need to add to these PHP files so they will correctly be recognized as plugins.


Try:

preg_match('~// First: (.*)\n// Second: (.*)~i', $str);

See it

Why is your regex wrong?

[\/\/\*] is a character class that either matches a / or a *.

But you seem to have // at the beginning of the string, so you'll never get a match.

What string will my current regex match?

Change your current input to have a / at the beginning and a newline after the second line:

$some_string =
'/ First: a string
/ Second: another string
';

See it


$some_string = <<<STR
// First: a string
// Second: another string

STR;

$match = preg_match('`// First: (.*)\n// Second: (.*)\n`i', $some_string);

echo $match;

Just tested this, it works. Are you sure there's a linebreak after the second line?


(Posted on behalf of the OP).

Answer:

I was trying to guess what pattern this would match. It ended up being this:

/*
* First: a string
* Second: another string
*/
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜