collecting values in array from tags ??

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

collecting values in array from tags ??

Post 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.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post 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.
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

Post 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];
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

PREG_PATTERN_ORDER is the default, so you don't really need that flag. but, it doesn't hurt anything.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Post Reply