adrianogf
adrianogf

Reputation: 171

php preg_match How to

I'm trying to get a "ref code" from the html but just the "ref" when label is P

Ex: 031-0132-806-02

How can I do this using preg_match???

How can I get this information with preg_match?

{
label: 'P',
available: false, 
ref: '031-0132-806-02'
},
{
label: 'M',
available: false, 
ref: '031-0132-806-03'
}] 
} 
},

Upvotes: 0

Views: 519

Answers (2)

AbsoluteƵERØ
AbsoluteƵERØ

Reputation: 7870

If the numbers are always in the same pattern you can do it with this:

<?php
    $string = "{
    label: 'P',
    available: false, 
    ref: '031-0132-806-02'
    },
    {
    label: 'M',
    available: false, 
    ref: '031-0132-806-03'
    }] 
    } 
    },";

    preg_match_all('![0-9]{3}\-[0-9]{4}\-[0-9]{3}\-[0-9]{2}!',$string,$matches);

    print_r($matches);

?>

Updated Let's say this is a crawler for the data.

<?php

$url = 'http://www.urltocapture...';

function crawlSite($url){
    $refIDs = array();
        $string = file_get_contents($url);

        preg_match_all('!\items: +?\[[^]]+\]!s',$string,$sets);
        foreach($sets as $items){
            foreach($items as $item){

                $cleanupPattern = array('!\t+!','! +!','!(\r\n|\n|\r)+!','! +!');
                $cleanupReplacements = array(' ',' ',""," ",);
              $item = preg_replace($cleanupPattern,$cleanupReplacements,$item);
              //echo $item."\n";    

            preg_match_all('!label: \'P\'[^\}]+([0-9]{3}\-[0-9]{4}\-[0-9]{3}\-[0-9]{2})[^\}]+}!',$item,$item_match);

                if(!empty($item_match[1][0])){
                    $refIDs[] = $item_match[1][0];
                }
            }
        }
        return $refIDs;

}

$refIDs = crawlSite($url);
print_r($refIDs);

?>

Upvotes: 2

HamZa
HamZa

Reputation: 14921

Using a foreach loop:

$string = <<<WUT
{
label: 'P',
available: false, 
ref: '031-0132-806-02'
},
{
label: 'M',
available: false, 
ref: '031-0132-806-03'
}] 
} 
},
WUT;

$ref = array();

preg_match_all('/(?P<labels>{\s*label:.*?})/s', $string, $m);

foreach($m['labels'] as $code){
    if(strpos($code, "label: 'P'")){
        preg_match('/ref: \'(.*?)\'/', $code, $n);
        $ref[] = $n[1];
    }
}

print_r($ref);

Upvotes: 0

Related Questions