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 pat开发者_StackOverflowterns. 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.
> 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, en older PHP versions,( the /e
modifier has since 5.5 been deprecated).
preg_replace('...pattern..../e','strlen("$2") > 0?"$2":"$1"',$string);
精彩评论