gpt4 book ai didi

php - 正则表达式 | explode | str_split 匹配标题中的数字

转载 作者:行者123 更新时间:2023-12-04 15:06:56 25 4
gpt4 key购买 nike

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

$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 或其他任何方法来实现此目的?

最佳答案

你可以使用

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

参见 regex demo . 详细信息:

  • (?<![^\W_]) - 与 _ 的单词边界减去的位置(就在前面,必须有字符串的开头,或非字母数字字符)
  • n - n字符
  • (?:r?[_.]|umero_?) - 可选 r然后 _. , 或 umero和一个可选的 _字符
  • \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'

关于php - 正则表达式 | explode | str_split 匹配标题中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65955506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com