Php preg_replace, regexp

I am trying to extract zip codes from yell.com using php and preg_replace. I successfully retrieved the postal code, but only along with the address. Here is an example of <Preview> $ URL = " http://www.yell.com/ucs/UcsSearchAction.do?scrambleSeed=17824062&keywords=shop&layout=&companyName=&location=London&searchType=advance&broaderLocation=&clarifyIndex=0&clarifyOPSOTCLESCLPS - + LADIES | & ooa = & M = & ssm = 1 & lCOption32 = RES | CLOTHES + SHOPS + - + LADIES & bandedclarifyResults = 1 ";

// get the yell.com page in the line $ htmlContent = $ baseClass-> getContent ($ URL); // receive the zip code along with the address $ result2 = preg_match_all ("/(.*) </span> /", $ htmlContent, $ matches);

print_r ($ matches);

The above code produces something like Array ([0] => Array ([0] => 7, Royal Parade, Chislehurst, Kent BR7 6NR [1] => 55, Monmouth St, London, WC2H 9DG .... problem that I have that I don’t know how to retrieve only the postal code without an address, because it does not have the exact number of digits (sometimes it has 6 digits, and sometimes it only 5 times). Basically I have to extract the extended 2 words from each array, Thank you in advance for your help!

+3
source share
2

:

# your array item
$string = "7, Royal Parade, Chislehurst, Kent BR7 6NR";

# split on spaces
$bits = preg_split('/\s/', $string);

# last two bits
end($bits);
$postcode = prev($bits) . " " . end($bits);

echo $postcode;

, :

0

, :

\b\w+\s+\w+$

, : , , , , .

<?php

$text = "7, Royal Parade, Chislehurst, Kent BR7 6NR";
$result =   preg_match("/\\b\\w+\\s+\\w+$/", $text, $matches);
print_r($matches);

?>

:

Array
(
    [0] => BR7 6NR
)

, \s* .., $ .

0

Source: https://habr.com/ru/post/1745610/


All Articles