dsf12123 2014-04-02 14:17
浏览 25
已采纳

PHP:正则表达式替换字符串中的#3

I want to make links using shortcuts following the pattern: controller/#/id. For example: a#3 must be rewritten to /actions/view/3, and t#28 must be a link to /tasks/view/28. I think preg_replace is an "easy" way to achieve this, but I'm not that good with regular expressions and I don't know how to "reuse" the digits from the search-string within the result. I think I need something like this:

$search = array('/a#\d/', '/t#\d/');
$replace = array('/actions/view/$1', '/tasks/view/$1');
$text = preg_replace($search, $replace, $text);

Can someone point me in the right direction?

  • 写回答

2条回答 默认 最新

  • doushe2513 2014-04-02 14:23
    关注

    You can "reuse" the numbers from the search strings using capturing groups, denoted by brackets ().
    Try this -

    $text = "a#2 a#3 a#5 a#2 t#34 t#34 t#33 t#36";
    $search = array('/\ba#(\d+)\b/', '/\bt#(\d+)\b/');
    $replace = array('/actions/view/$1', '/tasks/view/$1');
    $text = preg_replace($search, $replace, $text);
    var_dump($text);
    /**
    OUTPUT-
    string '/actions/view/2 /actions/view/3 /actions/view/5 /actions/view/2 /tasks/view/34 /tasks/view/34 /tasks/view/33 /tasks/view/36' (length=123)
    **/
    

    The above answer works, but if you need to add more of those search values, you can store those keys in separate array and you can use preg_replace_callback.
    This also does the same thing, but now, you only need to add more (alphabets)keys in the array and it will replace it accordingly.
    Try something like this-

    $arr = Array(
        "a"=>   "/actions/view/",
        "t"=>   "/tasks/view/"
    );
    $text = preg_replace_callback("/\b([a-z]+)#(\d+)\b/", function($matches) use($arr){
        var_dump($matches);
        return $arr[$matches[1]].$matches[2];
    },$text);
    var_dump($text);
    /**
    OUTPUT-
    string '/actions/view/2 /actions/view/3 /actions/view/5 /actions/view/2 /tasks/view/34 /tasks/view/34 /tasks/view/33 /tasks/view/36' (length=123)
    **/
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 全志H618ROM新增分区
  • ¥20 jupyter保存图像功能的实现
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况