3

I'm giving an example so you can understand what I want to achieve. I got this titles:

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

Until now I had tried:

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

But this is a limited solution because it does not work on all titles. How can I use Regex,explode,str_split, or anything else to achieve this?

Marinario Agalliu
  • 989
  • 10
  • 25

1 Answers1

2

You can use

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

See the regex demo. Details:

  • (?<![^\W_]) - a word boundary with _ position subtracted (right before, there must be start of string, or a non-alphanumeric char)
  • n - n char
  • (?:r?[_.]|umero_?) - either an optional r and then _ or ., or umero and an optional _ char
  • \s* - zero or more whitespace chars
  • \K - match reset operator
  • \d+ - one or more digits.

See the 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";
}

Output:

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'
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563