Hi,

I am in need of parsing some html code.
Here is an example of what I am trying to do, but not quite sure how to do it.

<tbody><tr>   <td>1.</td>   <td><a href="something.php?y=US&amp;id=197003">Some Name Here</a></td>   <td>City, STATE</td>   <td class="noWrap"></td>   <td class="noWrap">123-456-7890</td></tr><tr class="altRow">   <td>2.</td>   <td><a href="something.php?y=US&amp;id=113762">Another Name</a></td>   <td>City, STATE</td>   <td class="noWrap"></td>   <td class="noWrap">123-456-7890</td></tr>

I need to catch the id of each of those hrefs in the code. The "something.php?y=US&amp;id=" is constant so that will not change. The data is in a table, and I can get all of the other information from the table, but I can't pull the id from those links. Any help or suggestions would be greatly appreciated.

Thanks,

Recommended Answers

All 2 Replies

It can be done like this:

<?php
$html = '<tbody><tr>   <td>1.</td>   <td><a href="something.php?y=US&amp;id=197003">Some Name Here</a></td>   <td>City, STATE</td>   <td class="noWrap"></td>   <td class="noWrap">123-456-7890</td></tr><tr class="altRow">   <td>2.</td>   <td><a href="something.php?y=US&amp;id=113762">Another Name</a></td>   <td>City, STATE</td>   <td class="noWrap"></td>   <td class="noWrap">123-456-7890</td></tr>';

function get_id($data)
{
	preg_match_all('/< *a[^>]*href *= *["\']?([^"\']*)/i', $data, $matches);
	$result = array();
	foreach($matches[1] as $id)
	{
		$r = explode('id=',$id);
		$result[] = $r[1];
	}
	return $result;
}
print_r(get_id($html));
?>

Using preg_match_all to get all href in a tags and then searching for the right pattern, the constant, I set "id=" as constant in the explode() function but you can set also explode('something.php?y=US&amp;id=',$id); if you want and you will get the same result:

Array
(
    [0] => 197003
    [1] => 113762
)

an array of IDs, bye :)

Thanks a bunch cereal! I actually was really close to this, using the preg_match_all(), it was the explode that I was forgetting! Thanks. I really appreciate it. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.