dqvy87517 2013-03-14 01:11
浏览 20
已采纳

在preg_match中指定$ matches中的内容

I have been researching this for a half hour and still can't figure it out. I am sure it is simple.

I want to match an id but only if it has "ID: " in front.

<?php
$string1 = "Payment: 1474";
$string2 = "Payment ID: 1474";

preg_match('/ID: ([0-9]){1,7}$/', $string1, $matches);

//array(0){} Good! This is the expected result.

preg_match('/ID: ([0-9]){1,7}$/', $string2, $matches);

//array(2) { [0]=> string(8) "ID: 1474" [1]=> string(1) "4" }
//I am glad it finds a match, but I want matches[0] to be only the id, 1474

?>

In other words, I need to find a match but I also need to specify what goes into the array.

Since I am having trouble learning this, I would appreciate if you don't just answer with code but also explain what it does. Thanks!

  • 写回答

3条回答 默认 最新

  • douxian6086 2013-03-14 01:13
    关注

    Try this:

    preg_match('/ID: ([0-9]{1,7})$/', $string2, $matches);
    

    In your code, the capture group was just matching one character. This matches 1-7 numbers inside the capture group.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义