[thelist] PHP regex script returns empty array

Symeon Charalabides symeon at systasis.com
Sat Apr 11 06:41:36 CDT 2009


Hi Madhu,

If you look at the output of var_dump closely, you'll see that $results 
is an array of one element. That element is another array that contains 
all you results and that is the array that is output by your "echo $v" 
statement.

The simplest fix is to add the line

$matches = $results[0];

after the preg_match line, then do the foreach on $matches instead of 
$results.


Madhu Menon wrote:
> RIght, so I'm a PHP newbie, so maybe I'm missing something obvious here.
> 
> What I'm trying to do is extract all the 10-digit numbers beginning with 
> 9 from a mass of text. The regex I'm using seems to be OK. The problem 
> is with the script that displays the results.
> 
> Here's what I'm using:
> 
> 
> 
> <?php
> 
> $rawtext=$_POST["JDS"];
> 
> $pattern = '/\b9[0-9]{9}/';
> 
> preg_match_all ($pattern, $rawtext, $results);
> 
> foreach ($results as $v) {
>     echo $v;
> }
> 
> 
> // var_dump($results);
> 
> 
> ?>
> 
> 
> JDS is the name of the HTML form element capturing the input text. 
> $pattern is obviously the regex.
> 
> So in theory, this should display all the matches found in the text, right?
> 
> Except that it doesn't.
> 
> The only output from that script is the word "Array"
> 
> What makes it weirder is that when I used var_dump to check the contents 
> of the array, it displays the matches just fine. Here is a sample output:
> 
> array(1) { [0]=> array(36) { [0]=> string(10) "9845439405" [1]=> 
> string(10) "9880000211" [2]=> string(10) "9972584305" [3]=> string(10) 
> "9845347327" [4]=> string(10) "9886742603" [5]=> string(10) "9739044591" 
> [6]=> string(10) "9986018897" [7]=> string(10) "9900596375" [8]=> 
> string(10) "9972008039" [9]=> string(10) "9741199007" [10]=> string(10) 
> "9845075685" [11]=> string(10) "9886730267" [12]=> string(10) 
> "9844234519" [13]=> string(10) "9916045790" [14]=> string(10) 
> "9980139070" [15]=> string(10) "9739774949" [16]=> string(10) 
> "9902532000" [17]=> string(10) "9980082324" [18]=> string(10) 
> "9731300083" [19]=> string(10) "9886734884" [20]=> string(10) 
> "9845947753" [21]=> string(10) "9880276754" [22]=> string(10) 
> "9986370202" [23]=> string(10) "9845364884" [24]=> string(10) 
> "9743999629" [25]=> string(10) "9886736757" [26]=> string(10) 
> "9845670085" [27]=> string(10) "9980177506" [28]=> string(10) 
> "9886133381" [29]=> string(10) "9886897583" [30]=> string(10) 
> "9886298328" [31]=> string(10) "9886328642" [32]=> string(10) 
> "9845194794" [33]=> string(10) "9845418801" [34]=> string(10) 
> "9845770764" [35]=> string(10) "9845770764" } }


-- 

Symeon Charalabides (cosmopolite trainee)
-----------------------------------------
http://www.systasis.com
http://twitter.com/bluesymeon
http://www.linkedin.com/in/symeon
http://www.last.fm/user/bluesymeon




More information about the thelist mailing list