[thelist] Extract a specific but changing part of a string (PHP)

Barry Woolgar barry at burnthebook.co.uk
Fri May 16 09:38:04 CDT 2008


Stef says:

> I have a string which looks like this:
>
>	...<br />% countries: <b>73%</b><br />% population: <b>98%</b><br
/>% economy (GDP): ....
>
> Now, I would like to extract the value which is to be found behind the
"population: <b>"


Stand back! http://xkcd.com/208/

Ironically I'm not sure I've got this right but regular expressions are what
you are looking for:

$matches = array(); // were your result will go
$pattern = '/population: <b>(.+)</b>/'; // your regular expression
$string = '<br />% countries: <b>73%</b><br />% population: <b>98%</b><br
/>% economy (GDP)'; // for example

if (preg_match($pattern, $string, $matches)) // returns number of matches (0
means no match)
	{
	// $matches[0] = 'population: <b>98%</b>' - The part of the string
that matches the whole pattern
	// $matches[1] = '98%' - The part that matches the first pair of
parentheses in the regex pattern
	}

You may also want to look at preg_match_all() and also tweak the regular
expression to match a more specific set (at the moment it'll take whatever
is between those <b> tags, you may only want full percentages and not
anywhere it might say 'n/a'

http://uk3.php.net/preg_match

PS. I've not been able to test this yet :)

Hope that helps

Barry

No virus found in this outgoing message.
Checked by AVG. 
Version: 7.5.524 / Virus Database: 269.23.16/1445 - Release Date: 15/05/2008
19:25
 




More information about the thelist mailing list