Welcome to WebmasterWorld Guest from 54.226.27.104

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Finding a sequence of numbers in a string

     

Crump

2:52 pm on Jun 15, 2009 (gmt 0)

10+ Year Member



I have a string that will contain a sequence of consecutive numbers at some point. For instance

390 joe smith 1923892 baltimore, md

I need to extract the 0923892 out of this string. I can't use the spaces as a method of finding where it is. How can I extract the 7 digit number?

jatar_k

3:41 pm on Jun 15, 2009 (gmt 0)

WebmasterWorld Administrator jatar_k is a WebmasterWorld Top Contributor of All Time 10+ Year Member



you need to find some reliable pattern to pull it out

where does the data come from? It must be generated with some consistency if it comes from a single source, if it is from multiple sources then you may need a pattern per source.

once you can identify the pattern then you can make decisions on how to best extract it

nalin

4:36 pm on Jun 15, 2009 (gmt 0)

10+ Year Member



use a regular expression

ie


preg_match('/[0-9]{7}/',$string,$matches);
var_dump($matches);

jatar_k

5:36 pm on Jun 15, 2009 (gmt 0)

WebmasterWorld Administrator jatar_k is a WebmasterWorld Top Contributor of All Time 10+ Year Member



that does assume though that the desired 7 digit number is the only 7 digit number that will ever occur in the data, which may not be the case

g1smd

5:40 pm on Jun 15, 2009 (gmt 0)

WebmasterWorld Senior Member g1smd is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month



Is the number always directly preceded and followed by spaces and/or punctuation?

NomikOS

5:56 pm on Jun 15, 2009 (gmt 0)

10+ Year Member



first approah:
<?php 
$str = '1234567 str 999999999586 390 joe smith popopopopopopopopo ';
$str .= '1923892 baltimore, md 787878 1234568 8586552895 1234569';

if (preg_match_all("/[^\d]+(\d{7})[^\d]+/si", $str, $extract, PREG_SET_ORDER))
{
foreach ($extract as $number)
{
$extratctedNumbers[] = $number[1];
}
}

var_dump($str);
die(var_dump($extratctedNumbers));
?>

but. this not extract numbers in the extrems!

NomikOS

6:03 pm on Jun 15, 2009 (gmt 0)

10+ Year Member



Quick && dirty solution:

<?php 
$str = '1234567 str 999999999586 390 joe smith popopopopopopopopo ';
$str .= '1923892 baltimore, md 787878 1234568 8586552895 1234569';

if (preg_match_all("/(\d+)/si", $str, $extract, PREG_SET_ORDER))
{
foreach ($extract as $number)
{
if (strlen($number[1]) == 7)
$extratctedNumbers[] = $number[1];
}
}

var_dump($str);
die(var_dump($extratctedNumbers));
?>

this is OK I think...
 

Featured Threads

Hot Threads This Week

Hot Threads This Month