-1

i have the following html structure :

<div data-provincia="mi" data-nazione="it" ecc...

I'm trying to take "mi" with preg_match function. This is my code :

$pattern = '/data-provincia=*"[a-zA-Z]*"/';
preg_match($pattern,$element,$provincia);

I think that the code is right but it doesn't match with anything. Where i'm wrong? Thanks.

Isky
  • 1,328
  • 2
  • 14
  • 33

4 Answers4

1

You might want to use the quantifier + (1 or more) next to the character class between brackets, and remove the first star. Also added a subtpattern for you to get exactly the part you want. Give it a try :

$pattern = '/data-provincia="([a-zA-Z]+)"/';
preg_match($pattern,$element,$provincia);
echo $provincia[1];
Calimero
  • 4,238
  • 1
  • 23
  • 34
1
$element = '<div data-provincia="mi" data-nazione="it" ecc...>';
$pattern = '/<div[^>]*data-provincia=\"([^\"]+)\"[^>]*>/';
preg_match($pattern,$element,$provincia);
print_r($provincia[1]);
Mayur Koshti
  • 1,794
  • 15
  • 20
1

In addition to my comment, for this simple attribute you can use the following regex:

$regex = '/data-provincia="([^"]*)/i';
preg_match($regex,$element,$matches);
echo $matches[1];

Basically match everything except a double quote as many times as possible (or none). But please at least consider using a Parser for this task, regular expressions were not meant to deal with it.

Jan
  • 42,290
  • 8
  • 54
  • 79
1

Its working fine for me

$element = '<div data-provincia="mi" data-nazione="it"></div>';
$pattern = '/data-provincia=*"[a-zA-Z]*"/';
$matches= array();
preg_match($pattern,$element, $matches);
if (!empty($matches)) {
    foreach ($matches as $eachOne) {
        //code to remove unwanted
        $text = trim(preg_replace('/^data-provincia\=/', '', $eachOne), '""');
        echo " $eachOne; $text";
    }

}
Santhy K
  • 829
  • 1
  • 7
  • 12