正则表达式:查找号码之前和之后

时间:2018-11-29 02:35:43

标签: php regex

我是regex的新手,被卡住了,所以需要帮助才能通过regex获得ID 13,谢谢:)

$str = 'How many points would you like to add or subtract?
(Note: Key a negative number to deduct points)

The following user will be updated:

ID: 13
Name: Alex
Company: Unknown
Current Points: 2';

$id = preg_match_all('/ID: (\d+)/', $str); 
print_r($id); // 1

希望找到一种匹配“ 13”而不是“ 1”的方法

3 个答案:

答案 0 :(得分:0)

使用

(?<=ID: )

标识ID:开头的位置,然后将数字与\d+匹配:

$str = "How many points would you like to add or subtract?
(Note: Key a negative number to deduct points)

The following user will be updated:

ID: 13
Name: Alex
Company: Unknown
Current Points: 2";

preg_match_all('/(?<=ID: )\d+/', $str, $matches);

请注意,如果您仅查找单个匹配项,则应使用preg_match而不是preg_match_all

答案 1 :(得分:0)

$s = "How many points would you like to add or subtract?
(Note: Key a negative number to deduct points)

The following user will be updated:

ID: 13
Name: Alex
Company: Unknown
Current Points: 2";

preg_match("#ID: (?<id>\d+)#", $s, $matches);
print_r($matches['id']); // output: 13

答案 2 :(得分:0)

尝试使用non-captureing组的ID和capturing组的数字,例如$re = '/(?:ID: )(\d+)/m';。参见REGEX

<?php 
$re = '/(?:ID: )(\d+)/m';
$str = 'How many points would you like to add or subtract?
(Note: Key a negative number to deduct points)

The following user will be updated:

ID: 13
Name: Alex
Company: Unknown
Current Points: 2';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
echo $matches[0][1];

演示: https://3v4l.org/bChBi