dougou7008 2012-12-03 19:10
浏览 37
已采纳

PHP正则表达式帮助(preg_replace)[关闭]

Lets say I have the string: "Test [[1294]] example"

How could I do a preg_replace() that would extract the number from the double brackets?

Could someone please advise me to what the (Greedy) expression for getting that number would be? -it'll always be a integer within double brackets.

Thanks alot.

  • 写回答

2条回答 默认 最新

  • dsjuimtq920056 2012-12-03 19:13
    关注

    You might want to check out a tutorial.

    If you want to "extract" the number, there is no need for preg_replace. Use preg_match or preg_match_all (if there are multiple occurrences) instead:

    preg_match('/\[\[(\d+)\]\]/', $input, $matches);
    $integer = $matches[1];
    

    or

    preg_match_all('/\[\[(\d+)\]\]/', $input, $matches);
    $integerArray = $matches[1];
    

    If instead of "extract" you actually meant something like "how can I preg_replace this term and use the extracted integer number", you can use the same regular expression and refer to the captured integer, using $1:

    $output = preg_replace('/\[\[(\d+)\]\]/', 'Found this integer -> $1 <-', $input);
    

    Which would result in:

    Test Found this integer -> 1294 <- example
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”