【问题标题】:Regex | explode | str_split to match number in a title正则表达式 |爆炸 | str_split 匹配标题中的数字
【发布时间】:2021-05-03 10:24:48
【问题描述】:

我正在举一个例子,以便您了解我想要实现的目标。 我得到了这个头衔:

$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);

但这是一个有限的解决方案,因为它不适用于所有标题。如何使用Regexexplodestr_split 或其他任何方法来实现这一目标?

【问题讨论】:

  • 你尝试过任何正则表达式模式了吗?
  • 不,因为我不擅长...这就是为什么我要求任何可以使用 PHP 或 Regex 的解决方案
  • 这是否意味着您只想提取第一个数字?所有这些数字都是每个字符串中的第一个数字。
  • 有些情况不是第一个数字。但所需的数字总是在一些n.numeronr_ ecc 之后。
  • 每个标题的预期输出是什么?

标签: php regex string split explode


【解决方案1】:

你可以使用

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

请参阅regex demo详情

  • (?&lt;![^\W_]) - 减去_ 位置的单词边界(就在前面,必须有字符串开头,或非字母数字字符)
  • n - n 字符
  • (?:r?[_.]|umero_?) - 一个可选的r,然后是_.,或者umero 和一个可选的_ char
  • \s* - 零个或多个空白字符
  • \K - 匹配重置运算符
  • \d+ - 一位或多位数字。

PHP demo

$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'

【讨论】:

  • 成功了,非常感谢!答案将在 5 分钟内被接受。你是我今天的救星。编码愉快!
  • 通过后面的 +1 很好地解决了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-18
  • 1970-01-01
  • 1970-01-01
  • 2018-07-17
  • 2015-01-21
  • 2012-04-02
相关资源
最近更新 更多