-2

I'm trying to use PHP to do a search on strings inside [code] and [php] tags. However i cannot get that to work. Using the same regex on other BB tags I can successfully get a match but not on those tags.

I have this so far:

\[(?:code|php)\](.+?)\[\/(?:code|php)\]

This should match on the following content:

[code]
    this should be matched
[/code]

[php]
    this should be matched
[/php]

I'm using preg_replace_callback with an anonymous function but the function doesn't get called on those two tags. It get's called if I change the regex to match other tags but not those two.

SLC
  • 2,167
  • 2
  • 28
  • 46

3 Answers3

1

You're using ., which matches all characters except newline. Switch it to a construct that also matches newlines, such as [\s\S], or even use the flag /s:

\[(?:code|php)\]([\s\S]+?)\[\/(?:code|php)\]
~\[(?:code|php)\](.+?)\[\/(?:code|php)\]~s
Unihedron
  • 10,902
  • 13
  • 62
  • 72
  • Yeah. I just discovered that adding `/s` fixes the issue. I thought `/m` does the job but didn't. – SLC Feb 11 '15 at 04:15
1

I would also recommend matching [code] with [/code] and same with [php] and [/php]:

\[(code|php)\]([\s\S]+?)\[\/\1\]

In this case the actual code will be in match group 2. See this Regex 101 for more information.

David Faber
  • 12,277
  • 2
  • 29
  • 40
0

You don't really need to do regex. Consider:

function get_string_between($string, $start, $end){
    $string = " ".$string;
    $ini = strpos($string,$start);
    if ($ini == 0) return "";
    $ini += strlen($start);
    $len = strpos($string,$end,$ini) - $ini;
    return substr($string,$ini,$len);
}

$fullstring = "this is my [tag]dog[/tag]";
$parsed = get_string_between($fullstring, "[tag]", "[/tag]");

echo $parsed; // (result = dog)

taken from an answer

Community
  • 1
  • 1
taesu
  • 4,482
  • 4
  • 23
  • 41