求教大佬们 一个 关于正则替换的问题?

function a($reg = '',$cid = 0, $page = 1){
    
    
    //返回 list-$cid/$page/
    // list-1/2/
    return $url
}
$reg = 'list\-([0-9]+)\/([0-9]+)\/';

echo a($reg, 1, 2);

怎么在a函数里面 返回 list-1/2/ 。

注意:
不能写死 list , 因为 $reg 其实也是一个变量(正则表达式)。
后期可能改成 cate 就是返回 cate-1/2/
改成 category 就是返回 category-1/2/

阅读 2.8k
2 个回答

你都传了两个参数进去了,为什么还需要正则呢,直接拼接字符串就好了吧

function a($category, $cid, $page) {
    return "$category-$cid/$page/";
}

这种场景其实不应该使用正则,而是模板字符串

function a($template, $cid, $page) {
    return sprintf($template, $cid, $page);
}

a("list-%d/%d/", 1, 2);

补充

$input = "list-1/2/";
$pattern = '/(\w+)-(\d+)\/(\d+)\//';
$replacement = '$1-index-cid-$2-page-$3';
$output = preg_replace($pattern, $replacement, $input);

正则的拼接处理办法:

const c = new RegExp('^(\\-)*(\\d+)\\.(\\d{0,' + allOpt.ws + '})\.*$');
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题