正则表达式 | 分割字符串 | 拆分字符串以匹配标题中的数字

3

我将给出一个示例,以便您理解我想要实现的目标。 我得到了这些标题:

$t1 = "Disposizione n. 158 del 28.1.2012";
$t2 = "Disposizione n.66 del 15.1.2006";
$t3 = "Disposizione f_n_66 del 15.1.2001";
$t4 = "Disposizione numero 66 del 15.1.2018";
$t5 = "Disposizione nr. 66 del 15.1.2017";
$t6 = "Disposizione nr_66 del 15.1.2016";
$t7 = "Disposizione numero_66 del 15.1.2005";

到目前为止,我尝试过:

$output = explode(' ', $t1);

foreach ($output as $key => $value) {

if($value == 'n.' || $value == 'numero' || $value == 'n' || $value == 'nr' || $value == 'nr.') {
    $number= $output[($key+1)];
    break;
}
}

print_r($attoNumero);

但是这只是一个有限的解决方案,因为它无法适用于所有的标题。我该如何使用正则表达式explodestr_split或其他任何方法来实现这个目标?


你试过使用正则表达式模式吗? - Wiktor Stribiżew
这是指您只想提取第一个数字吗?所有这些数字都是每个字符串中的第一个数字。 - Wiktor Stribiżew
有些情况下,数字不是第一个。但所需的数字总是在某个 n.numeronr_ 之后。 - Marinario Agalliu
例子:Disposizione del 31.12.2007 n. 1272 - Marinario Agalliu
1
每个标题的预期输出是什么? - nice_dev
显示剩余2条评论
1个回答

2

您可以使用

if (preg_match('~(?<![^\W_])n(?:r?[_.]|umero_?)\s*\K\d+~i', $text, $match)) {
    echo $match[0];
}

查看正则表达式演示细节

  • (?<![^\W_]) - 单词边界,减去_位置(必须在字符串开头或非字母数字字符之前)
  • n - n个字符
  • (?:r?[_.]|umero_?) - 可选的r_.,或者umero和可选的_字符
  • \s* - 零个或多个空白字符
  • \K - 匹配重置操作符
  • \d+ - 一个或多个数字。

查看PHP演示

$texts = ["Disposizione n. 158 del 28.1.2012", "Disposizione n.66 del 15.1.2006","Disposizione f_n_66 del 15.1.2001", "Disposizione numero 66 del 15.1.2018", "Disposizione nr. 66 del 15.1.2017", "Disposizione nr_66 del 15.1.2016", "Disposizione numero_66 del 15.1.2005"];
foreach ($texts as $text) {
    if (preg_match('~(?<![^\W_])n(?:r?[_.]|umero_?)\s*\K\d+~i', $text, $match)) {
        echo $match[0] . " found in '$text'" . PHP_EOL;
    } else echo "No match in $text!\n";
}

输出:

158 found in 'Disposizione n. 158 del 28.1.2012'
66 found in 'Disposizione n.66 del 15.1.2006'
66 found in 'Disposizione f_n_66 del 15.1.2001'
66 found in 'Disposizione numero 66 del 15.1.2018'
66 found in 'Disposizione nr. 66 del 15.1.2017'
66 found in 'Disposizione nr_66 del 15.1.2016'
66 found in 'Disposizione numero_66 del 15.1.2005'

1
它运行正常,非常感谢!答案将在5分钟内被接受。你是我今天的救星。愉快编程! - Marinario Agalliu
1
用lookbehind +1很好地解决了。 - The fourth bird

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接