views:

16

answers:

1

Hi everyone,

Here's my code

$string = preg_replace("/rad\:([0-9]+)px\;\s+\/\*\sALT\[(.+)\*\/|rad\:([0-9]+)px\;/",("$2"?"$2":"$1"),$string);

Basically, in the regex I've got a pipe |, and I'm searching for two patterns. If there is a match to the first pattern (to the left of the pipe), then I want the it to be replaced with the second capturing group ($2), but if it's a match with the second pattern (to the right of the pipe), then I want it to be replaced with the first capturing group ($1);

The code I've tried doesn't work. Is this possible at all?

Thanks for any help.

+1  A: 

> PHP 5.3:

 preg_replace_callback('..pattern...',
    function($match){return empty($match[2]) ? $match[1]:$match[2];},
    $string);

< PHP 5.3:

 function _my_func($match) {
    return empty($match[2]) ? $match[1]:$match[2];
 }
 preg_replace_callback('..pattern...',
    '_my_func',
    $string);

Or:

preg_replace('...pattern..../e','strlen("$2") > 0?"$2":"$1"',$string);
Wrikken
Brilliant! Thanks so much. I'm using your third option.
Emmanuel