1

I want to use preg_replace_callback to replace all instances of a custom tag with markup. For instance, I'm using this code 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.

Simian
  • 1,622
  • 3
  • 17
  • 32

2 Answers2

2

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

manojlds
  • 290,304
  • 63
  • 469
  • 417
  • I tried this with preg_replace_callback('/\[tube\](.*)\[\/tube\]/s', ...); But it doesn't give me what I want. Note I am trying to capture the subexpression, but it doesn't get picked up. – Simian Apr 29 '11 at 04:35
  • I think it should work. It is working for me. Try using /sm just in case to see if it works for you. Basically /s makes (.*) to match newlines as well – manojlds Apr 29 '11 at 04:45
  • Excellent, just what I was looking for – Simian Apr 29 '11 at 04:46
1

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 )
Dan Blows
  • 20,846
  • 10
  • 65
  • 96