Reputation: 73
I am using regular expressions in php to match postcodes found in a string.
The results are being returned as an array, I was wondering if there is any way to assign variables to each of the results, something like
$postcode1 = first match found
$postcode2 = second match found
here is my code
$html = "some text here bt123ab and another postcode bt112cd";
preg_match_all("/([a-zA-Z]{2})([0-9]{2,3})([a-zA-Z]{2})/", $html, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
echo $val[0]; }
I am very new to regular expressions and php, forgive me if this is a stupid question.
Thanks in advance
Upvotes: 1
Views: 1724
Reputation: 816462
Update: In order to make this example work, you have to use PREG_PATTERN_ORDER
instead of PREG_SET_ORDER
(I thought you used it in your code, but obviously I read too fast ;)):
PREG_PATTERN_ORDER
Orders results so that$matches[0]
is an array of full pattern matches,$matches[1]
is an array of strings matched by the first parenthesized subpattern, and so on.
If you really want to, you can assign them to variables:
$postcode1 = $matches[0][0];
$postcode2 = $matches[0][1];
But it is easier to just access the array elements imo.
Or something more fancy:
for ($i = 0; $i < count($matches[0]); $i++) {
${'postcode'.$i+1} = $matches[0][$i];
}
But I would just do:
$postcodes = $matches[0];
and then access the postcodes via normal array access.
Upvotes: 2
Reputation: 26932
The following should work for PHP 5.3+:
$postcodearray = array_map(function($x) {return $x[0];}, $matches);
list($postcode1, $postcode2) = $postcodearray;
(Which of course could be combined into one line if you don't care about the array of postcodes itself.)
To get the array of postcodes it uses an anonymous function.
For the list()
construct, see this related question: Parallel array assignment in PHP
If you don't have PHP 5.3+ (or if that anonymous function is confusing) you can define a function "first" like so
function first($x) { return $x[0]; }
and then get the array of postcodes like so:
array_map("first", $matches)
Upvotes: 0
Reputation: 12050
foreach ($matches as $index => $val) {
$prefix ='postcode'.$index;
${$prefix} = $val;
}
Upvotes: 0