dtpyvb1873 2010-03-22 10:15
浏览 71
已采纳

preg_replace模式

i'm not very firm with preg_replace - in other Words i do not really understand - so i hope you can help me.

I have a string in a Text like this one: [demo category=1] and want to replace with the Content of Category (id=1) e.g. "This is the Content of my first Category"

This is my startpoint Pattern - that's all i have: '/[demo\s*.*?]/i';

Hope you can help?

  • 写回答

4条回答 默认 最新

  • duan1983 2010-03-22 10:30
    关注

    Firstly, you need to escape the square brackets as they are special characters in PCREs:

    '/\[demo\s*.*?\]/i';
    

    Secondly, it sounds like you want to do something with the digit at the end, so you'll want to capture it using parenthesis:

    '/\[demo\s*.*?=(\d+)\]/i';
    

    The braces will capture \d+ and store it in a reference. \d+ will match a string of numbers only.

    Finally, it sounds like you need to use preg_replace_callback to perform a special function on the matches in order to get the string you want:

    function replaceMyStr($matches)
    {
        $strNum = array("1"=>"first", "2"=>"second", "3"=>"third"); // ...etc
        return "This is the Content of my ".$strNum($matches[1])." Category.";
        // $matches[1] will contain the captured number
    }
    preg_replace_callback('/\[demo\s*.*?=(\d+)\]/i', "replaceMyStr", "[demo category=1]");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)