Page 1 of 1

collecting values in array from tags ??

Posted: Mon Nov 26, 2007 12:01 am
by PHPycho
Hello forums.
Supppose i had following format in a string

Code: Select all

$string = '<tag value="1">Name1</tag>
<tag value="2">Name2</tag>
:
:
<tag value="n">Namen</tag>';
I would like to collect those values and names in an array as

Code: Select all

$array['name'] = array('Name1', 'Name2', .., 'Namen');
$array['value'] = array('1', '2', .., 'n');
Any suggestions and hints are warmly welcome.

Posted: Mon Nov 26, 2007 12:04 am
by s.dot

Posted: Mon Nov 26, 2007 12:08 am
by CoderGoblin
preg_match_all storing the information to an array name passed in as the third parameter. The precise regular expression would very much depend on how accurately you could guarantee the html convention such as double quotes for value=, any other possible elemental attributes etc.

Posted: Mon Nov 26, 2007 4:39 am
by PHPycho
got the soln as:

Code: Select all

$string = '<tag value="1">Name1</tag>
<tag value="2">Name2</tag>
:
:
<tag value="n">Namen</tag>';  

$return = preg_match_all('/<tag\s+value="(.*?)">(.*?)<\/tag>/', $string, $matches, PREG_PATTERN_ORDER);
$array['name'] = $matches[2];
$array['value'] = $matches[1];

Posted: Mon Nov 26, 2007 5:39 am
by s.dot
PREG_PATTERN_ORDER is the default, so you don't really need that flag. but, it doesn't hurt anything.