Johnny
Johnny

Reputation: 35

Not having any luck with preg_match

im trying to parse a url for the last 2 / sections. i need to get the address (can get that) and the number(second section {ie:08078612,08248595} unless its at last and no address is present {last url list example} {ie: 8274180}) i optionally need to get the last 3 digits of the second only numbers section.{ie 612,595,180}

Im not having any luck heres my code so far.

$url_list[] = $url;

if(preg_match("/[0-9]/",substr(strrchr($url, '/'), 1))) {
    $url_list_mls[]= substr(strrchr($url, '/'), 2);
    $url_list_mls_last3[] = substr(strrchr($url, '/'), -3); 
} else {
    $url_list_mls[]= substr(strrchr($url, '/'), 1);
    $url_list_mls_last3[] = substr(strrchr($url, '/'), -3);
}

$url_list_addy[]= substr(strrchr($url, '/'), 1);

Example URLs (part of the full url endings as examples)

/a019/08078612/214-N-CREST-Avenue
/a019/08248595/111-N-Elroy-Avenue
/a019/8274180

im trying to make 3 lists, address (last section) number (second section) and last 3 numbers of the second section number.

Upvotes: 1

Views: 59

Answers (1)

AbsoluteƵERØ
AbsoluteƵERØ

Reputation: 7880

The original code is way complicated. You can capture all of your strings with preg_match_all in a single line. Since the street address part seems to be conditional, I've made it so in my pattern. Also by grouping the last 3 {3} in their own parenthesis we can use them as well. I wasn't sure if the a019 changed, so I've included it as well, just to show how it could be done.

<?php

$uris = array("/a019/08078612/214-N-CREST-Avenue",
"/a019/08248595/111-N-Elroy-Avenue",
"/a019/8274180",);

$pattern = "!/([a-zA-z][0-9]+)/([0-9]+([0-9]{3}))/?([A-Za-z0-9.-]+)?/?!";

$x=0;
foreach($uris as $uri){
    preg_match_all($pattern,$uri,$matches);

    $address[$x]['scode'] = $matches[1][0];
    $address[$x]['stcode'] = $matches[2][0];
    $address[$x]['last3'] = $matches[3][0];
    if(!empty($matches[4][0])){
        $address[$x]['staddr'] = $matches[4][0];
    }
    $x++;
}


print_r($address);

?>

$Address Output

Array
(
    [0] => Array
        (
            [scode] => a019
            [stcode] => 08078612
            [last3] => 612
            [staddr] => 214-N-CREST-Avenue
        )

    [1] => Array
        (
            [scode] => a019
            [stcode] => 08248595
            [last3] => 595
            [staddr] => 111-N-Elroy-Avenue
        )

    [2] => Array
        (
            [scode] => a019
            [stcode] => 8274180
            [last3] => 180
        )

)

Upvotes: 1

Related Questions