开发者

How to regex replace tag followed by newline?

I want to use preg_replace_callback to replace all instances of a custom tag with markup. For instance, I'm using this cod开发者_运维百科e to replace instances of "[tube]...[/tube]":

preg_replace_callback('/\[tube\](.*)\[\/tube\]/', array('MyClass', 'mycallback'), $data);

The problem is it will not match this:

[tube]
http://www.somesite.com
[/tube]

How can I do this?

Note: Yes I am already familiar with the PECL bbcode extension, as well as the PEAR library. But I want to do this without them.


You will have to use pattern modifiers.

s (PCRE_DOTALL) If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.

preg_replace_callback('/\[tube\](.*)\[\/tube\]/smU', array('MyClass', 'mycallback'), $data);

http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php


You're not matching the end of line characters right now, try using

Pattern: \[tube\]\s([^\s]*)\s\[/tube\]

EDIT: Here's the code working on mine (preg_match() uses the same matching library as preg_replace_callback()

$val = '[tube]
http://www.somesite.com
[/tube]';

preg_match('|\[tube\]\s([^\s]*)\s\[/tube\]|', $val, $matches);
print_r($matches);

Output:

Array ( [0] => [tube] http://www.somesite.com [/tube] [1] => http://www.somesite.com )
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜