PHP 逗号分隔的整数字符串中特定数值的正则表达式

PHP Regex for a specific numeric value inside a comma-delimited integer number string

我正在尝试使用 REGEX 从 $str 变量的输入中获取左右整数。但我一直把逗号和整数一起找回来。我只想要整数而不是逗号。我也尝试用 \d 替换通配符 . 但仍然没有解决。

$str = "1,2,3,4,5,6";

function pagination()
{
    global $str;
    // Using number 4 as an input from the string
    preg_match('/(.{2})(4)(.{2})/', $str, $matches);
    echo $matches[0]."\n".$matches[1]."\n".$matches[1]."\n".$matches[1]."\n";     
}

pagination();

鉴于你的函数名称,我假设你需要它来进行分页。

以下解决方案可能更简单:

$str = "1,2,3,4,5,6,7,8,9,10";
$str_parts = explode(',', $str);

// reset and end return the first and last element of an array respectively
$start = reset($str_parts);
$end = end($str_parts);

这可以防止您的正则表达式不得不处理您的数字进入两位数。

我相信您正在寻找正则表达式非捕获组

这是我所做的:

$regStr = "1,2,3,4,5,6";
$regex = "/(\d)(?:,)(4)(?:,)(\d)/";

preg_match($regex, $regStr, $results);
print_r($results);

给我结果:

Array ( [0] => 3,4,5 [1] => 3 [2] => 4 [3] => 5 )

希望对您有所帮助!

使用 CSV 解析器怎么样?

$str = "1,2,3,4,5,6";
$line = str_getcsv($str);
$target = 4;
foreach($line as $key => $value) {
if($value == $target) {
   echo $line[($key-1)] . '<--low high-->' . $line[($key+1)];
}
}

输出:

3<--low high-->5

或者正则表达式可以是

$str = "1,2,3,4,5,6";
preg_match('/(\d+),4,(\d+)/', $str, $matches);
echo $matches[1]."<--low high->".$matches[2];     

输出:

3<--low high->5

这些方法的唯一缺陷是数字是范围的起点还是终点。会是这样吗?