简体   繁体   English

PHP 正则表达式有帮助吗?

[英]PHP regular expression help?

I have problem writing a regular express which match with only div class name "classBig1" and has one anchor link as its child.我在编写仅与 div class 名称“classBig1”匹配并且有一个锚链接作为其子项的正则表达式时遇到问题。 Here is my code but it doesn't work:这是我的代码,但它不起作用:

preg_match_all ("/<div class=\"headline9\"><a[\s]+[^>]*?href[\s]?=[\s\"\']+".
                    "(.*?)[\"\']+.*?>"."([^<]+|.*?)?<\/a></div>/", 
                    $var, &$matches);

//example HTML: <div class="classBig1"><a href="http://yahoo.com">Go Index99</a></div>

I guess you had mentioned a wrong class-name in the code, but I consider it is "classBig1" - please take a look at the pattern that I have given.我猜你在代码中提到了一个错误的类名,但我认为它是“classBig1”——请看看我给出的模式。

I believe:我相信:

  1. You just wanted to get those "DIV" which has a class of "classBig1"您只是想获得那些具有“classBig1”的 class 的“DIV”
  2. These "DIVs" should have only one "A" tag.这些“DIV”应该只有一个“A”标签。

If yes, then don't hesitate to grab this piece of code:-).如果是,那么请不要犹豫,抓住这段代码:-)。

It seems to be working for me when I tried with a sample HTML code.当我尝试使用示例 HTML 代码时,它似乎对我有用。

Pattern:图案:

"/<div class=\"classBig1\"><a (.*)<\/a><\/div>/"

Hope it helps.希望能帮助到你。

If the HTML is as well formed as your example then the following regex is enough to solve your problem:如果 HTML 的格式与您的示例一样好,那么以下正则表达式足以解决您的问题:

  • <div class="classBig1"><a.*?</div>

The full PHP code would be:完整的 PHP 代码为:

preg_match_all('%<div class="classBig1"><a .*?</div>%', $html,
      $result, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($result[0]); $i++) {
    $match = $result[0][$i];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM