はい、可能です!この場合、次のソリューションをコーディングしました。
$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/
オンラインデモ
「柔軟」にしたので、より多くの値を追加できます。
$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
オンラインデモ
説明:
$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
注:これはPHP 5.3+でのみ機能します