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 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)