Jeffz
Jeffz

Reputation: 2105

php regex - need 2 groups captured

I need 2 groups captured: 1-expr (can be empty); 2-essi

see code below

$s = 'regular expr<span>essi</span>on contains';
function my_func($matches){

    //I need 2 groups captured
    //$matches[1] - "expr" (see $s before span) - can be empty, but I still need to capture it
    //$matches[2] - "essi" (between spans)
}
$pattern = "???";
echo preg_replace_callback($pattern, my_func, $s);

Upvotes: 0

Views: 56

Answers (1)

Martin Ender
Martin Ender

Reputation: 44259

$pattern = "~(\w*)<span>(\w+)</span>~";

This should do the trick.

If the second group should be able to match empty strings as well, replace the + by another *. Note that \w will match letters, digits and underscores. If that is too much or insufficient, replace it by an appropriate character class.

One more thing: I think the syntax for preg_replace_callback requires you to hand in the function name as a string.

Upvotes: 2

Related Questions