tags:

views:

57

answers:

2

Hello,

I have a string that looks like this:

blah blah blah
Team ID:</div>xxxxxxx
blah blah blah

where the x's are a 7 digit number.

How can I search for the "Team ID:" and then get the 7 digit number ahead of it? (In php).

+4  A: 

Use preg_match. It accepts an optional array into which it will place matches. Index 0 will contain the entire matched pattern, index 1 will contain the 7 digits matched by the (\d{7}):

$str = 'blah blah blah
Team ID:</div>1234567
blah blah blah';

$matches = array();
preg_match('/Team ID:<\/div>(\d{7})/', $str, $matches);

echo $matches[0]; // "Test ID:</div>1234567"
echo $matches[1]; // "1234567"

$team_id = (int)$matches[1]; // convert matches to an integer

Be sure to check the return value of preg_match; if it isn't 1 then the pattern wasn't able to match anything within your input string.

meagar
It's working fine, except for it says NULL right after the 7 digits.
Alex
like this: 9473796NULL
Alex
Try outputting your value with `var_dump`. If there's a NULL after it then the sample input you've provided doesn't match your actual input.
meagar
lol, nevermind. It was just some of my old code. Thanks a lot!
Alex
Glad to help. If this solves your problem, you should mark it as "accepted".
meagar
A: 

Here's a solution that doesn't use regular expressions:

$str='blah blah blah
Team ID:</div>1234567
blah blah blah';

$key='TeamID:</div>';

echo substr(strstr($str,$key),strlen($key),7);
stillstanding