反转正则表达式,从正则表达式创建字符串

我正在使用多语言网站,并选择使用每种语言的自定义网址,例如:
/en/cities/paris/
/nl/steden/paris/

两者都指向Cities控制器的Index方法.

在每个页面上都有一个切换语言的选项,它会查看我的路线以匹配控制器,视图和语言.

因此,如果我在荷兰语页面上,它会找到英文版的正确网址,这将是“城市”而不是“steden”.

一切正常,直到我开始使用更复杂的正则表达式.

我有这些正则表达式将匹配我想要的URL:

#^en/cities/([^/]+?)/$#
#^nl/steden/([^/]+?)/$#

在我的代码中,我可以访问匹配的变量,在此示例中为“paris”.是否可以“反转”这个正则表达式并打印’en / cities / paris /’

如果不是..考虑到URL是不同的,我将如何开始链接到同一页面的不同版本…最好将其尽可能地编程.

一个有点类似的问题,有人回答(http://stackoverflow.com/a/7070734/616398)正则表达式的本质是匹配无数的结果..所以它可能是不可能的.

很容易从字符串/ URL转到一组匹配的标准,以便在MVC中使用,但另一种方式……不用说,不幸的是.

是的,这是可能的!对于这种情况,我编写了以下解决方案:
$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/

Online demo

我已经使它“灵活”,所以你可以添加更多的值!

$regex = '#^en/cities/([^/]+?)/region/([^/]+?)$#'; // <<< changed
$replace = array('paris','nord'); // <<< changed

$result = preg_replace_callback('#^\^|\([^)]*\)|\$$#',-1));
echo $result; // en/cities/paris/region/nord

Online demo

说明:

$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
},-1)); // substr($regex,-1) => Get ride of the delimiters
echo $result; // output o_o

Note: This works only on PHP 5.3+

相关文章

正则替换html代码中img标签的src值在开发富文本信息在移动端...
正则表达式
AWK是一种处理文本文件的语言,是一个强大的文件分析工具。它...
正则表达式是特殊的字符序列,利用事先定义好的特定字符以及...
Python界一名小学生,热心分享编程学习。
收集整理每周优质开发者内容,包括、、等方面。每周五定期发...