是的,这是可能的!对于这种情况,我编写了以下解决方案:
$regex = '#^en/cities/([^/]+?)/$#';
$replace = array('paris');
$result = preg_replace_callback('#^\^|\([^)]*\)|\$$#', function($m)use($replace){
static $index = 0;
if($m[0] === '^' || $m[0] === '$'){return '';}
if(isset($replace[$index])){
return $replace[$index++];
}
return $m[0];
}, substr($regex, 1, -1));
echo $result; // en/cities/paris/
在线演示
I've made it "flexible" so you can add more values to it !
$regex = '#^en/cities/([^/]+?)/region/([^/]+?)$#'; // <<< changed
$replace = array('paris', 'nord'); // <<< changed
$result = preg_replace_callback('#^\^|\([^)]*\)|\$$#', function($m)use($replace){
static $index = 0;
if($m[0] === '^' || $m[0] === '$'){return '';}
if(isset($replace[$index])){
return $replace[$index++];
}
return $m[0];
}, substr($regex, 1, -1));
echo $result; // en/cities/paris/region/nord
Online demo
Explanation:
$regex = '#^en/cities/([^/]+?)/region/([^/]+?)$#'; // Regex to "reverse"
$replace = array('paris', 'nord'); // Values to "inject"
/* Regex explanation:
# Start delimiter
^\^ Match "^" at the begin (we want to get ride of this)
| Or
\([^)]*\) Match "(", anything zero or more times until ")" is found, ")"
| Or
\$$ Match "$" at the end (we want to get ride of this)
# End delimiter
*/
$result = preg_replace_callback('#^\^|\([^)]*\)|\$$#', function($m)use($replace){
static $index = 0; // Set index 0, note that this variable is only accessible in this (anonymous) function
if($m[0] === '^' || $m[0] === '$'){return '';} // Get ride of ^/$ at the begin and the end
if(isset($replace[$index])){ // Always check if it exists, for example if there were not enough values in $replace, this will prevent an error ...
return $replace[$index++]; // Return the injected value, at the same time increment $index by 1
}
return $m[0]; // In case there isn't enough values, this will return ([^/]+?) in this case, you may want to remove it to not include it in the output
}, substr($regex, 1, -1)); // substr($regex, 1, -1) => Get ride of the delimiters
echo $result; // output o_o
Note: This works only on PHP 5.3+