开发者

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 开发者_如何学Gohttp://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.


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?


use print_r($matches)

edited:

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜