Michael
Michael

Reputation: 6405

php preg_match pattern to extract a specific information, regex

I need to extract a specific Id from a html document but the problem is that the id must not "be used".

Here is the html content http://pastebin.com/wF2dx8JZ

As you may see there are different html blocks . Some of them contain the "Used" word so I need to extract only the first id which is not used. Basically I can write a simple pattern like : $pattern = "/javascript:tw(.*))/"; preg_match_all($pattern, $content, $matches); $id = $matches[1][0];

However in this case I'm also getting the "ids" which are used so I don't know how to exclude them from the equation . Any idea would be highly appreciated.

Upvotes: 1

Views: 1632

Answers (3)

potatoe
potatoe

Reputation: 1070

It depends a little on how your html "blocks" are stored in memory. Do you have an array of strings, each of which contains the html for one "block"? If not, can you make one by using PHP's explode() function? (For example, $html_blocks = explode("<!---->", $all_html); if that comment sequence is actually a part of your data rather than something you added.)

Once you have the blocks separated, then you can use preg_grep() to find the blocks which don't contain 'used'. So do something like this:

$unused_blocks = preg_grep("Used", $html_blocks, PREG_GREP_INVERT);

If you want to be more careful about matching, you can use another regexp as the first parameter.

Now you have $unused_blocks, which is an array of html strings that are 'not used'. You can then use your already working preg_match() pattern to extract the ids for each one.

Hope this helps, or gets you closer anyway.

Upvotes: 0

apis17
apis17

Reputation: 2855

use print_r($matches)

edited:

preg_match('#\(([^)]+)\)#', $matches[1][0], $m);
echo $m[1];

Upvotes: 0

landons
landons

Reputation: 9547

Try this:

if (preg_match_all('~Used.*?javascript:tw\((\d+)\)~ig', $content, $matches))
{
    print_r($matches);
}

But, you should know, there's a 99.9% chance of a better way of doing this. Do you have access to the data source?

Upvotes: 1

Related Questions