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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化