【发布时间】:2018-04-26 13:56:41
【问题描述】:
我有这个preg_match_all() 的正则表达式,它在 regex101.com 上正确匹配,但在我的代码上却没有。
我试图解析的 html 元素如下所示:
<a class="profile-link" href="CompanyProfile.aspx?PID=4813&amp;country=211&amp;practicearea=0&amp;pagenum=" title="1-844-Iran-Law">Amin Alemohammad</a>
在整个 html curl 结果中找到。每个块都有以下例如:
<li style="opacity: 1;">
<a class="profile-link" href="CompanyProfile.aspx?PID=4813&country=211&practicearea=0&pagenum=" title="1-844-Iran-Law">Amin Alemohammad</a>
<!--<a class="profile-link" href="javascript:void(0)" title="1-844-Iran-Law">Amin Alemohammad</a>-->
<img src="/Images/Uploaded/Photos/4813_1844IranLaw.png" style="max-width:140px; max-height:140px">
<div class="results-profile">
<h2>Amin Alemohammad</h2>
<p><strong>Firm:</strong> 1-844-Iran-Law <br> <strong>Country:</strong> USA</p>
<p class="blue"><strong>Practice Area:</strong> Iranian Desk</p>
<ul>
<li class="tel-icon" style="opacity: 1;">Tel: +1-202-465-8692</li>
<li class="fax-icon" style="opacity: 1;">Fax: +1-202-776-0136</li>
<li class="email-icon">Email: <a style="position:relative; z-index:9999;" href="mailto:amin@1844iranlaw.com">amin@1844iranlaw.com</a></li>
</ul>
</div><!-- results profile -->
<img class="practice-logo" src="/Images/Uploaded/Logos/4813_1844IranLaw.png" style="max-width:185px; max-height:70px;">
<a class="results-btn contact-btn" href="CompanyProfile.aspx?PID=4813&country=211&practicearea=0&pagenum=" title="View Full Profile">VIEW FULL PROFILE</a>
<!--<a class="results-btn contact-btn" href="CompanyProfile.aspx?PID=4813&country=211&practicearea=0&pagenum=" title="1-844-Iran-Law">CONTACT</a>-->
<a class="results-btn website-btn" href="http://www.1844iranlaw.com" title="www.1844iranlaw.com">VIEW WEBSITE</a>
</li>
</li>
正则表达式结果
Group 1. 54-58 `4813` // company profile
Group 2. 71-74 `211` // country id
Group 3. 92-93 `0` // practice area
Group 5. 115-129 `1-844-Iran-Law` // company name
Group 6. 131-147 `Amin Alemohammad` // Person's name
我拥有的是:
preg_match_all('/<a class="profile-link" href="CompanyProfile\.aspx\?PID=(.*?)&country=([0-9]{1,}?)&practicearea=([0-9]{1,10}?)&pagenum=\?" title="(.*?)">(.*?)<\/a>/', $result, $match, PREG_PATTERN_ORDER);
dd($match);
返回
array:6 [▼
0 => []
1 => []
2 => []
3 => []
4 => []
5 => []
]
匹配数是正确的 -> 字符串模式中有 5 个匹配,但我不知道为什么它返回空值。
提前感谢您的任何帮助,因为我尝试了很多方法,但不是正确的方法或看到我错过了什么。
【问题讨论】:
-
在你的正则表达式中有一个
\?,它不属于那里,在pagenum=之后。当你删除它工作正常。/<a class="profile-link" href="CompanyProfile\.aspx\?PID=(.*?)&amp;country=([0-9]{1,}?)&amp;practicearea=([0-9]{1,10}?)&amp;pagenum=\?" title="(.*?)">(.*?)<\/a>/应该是/<a class="profile-link" href="CompanyProfile\.aspx\?PID=(.*?)&amp;country=([0-9]{1,}?)&amp;practicearea=([0-9]{1,10}?)&amp;pagenum=" title="(.*?)">(.*?)<\/a>/ -
在数组中仍然得到相同的空值。
-
它适用于我使用上述正则表达式和您的示例结果。
-
只选择那段代码,是的,它有效。但我从 curl 结果的
<body>(...)</body>中获取全部内容。可能有些东西可能会破坏它并返回空值 -
我不知道整个内容是什么样的,所以我真的不能帮你调试它。也许
<a...>和</a>之间的内容中有换行符?如果是这样,您可以在正则表达式的末尾添加smodifier。或尝试 DOMDocument 答案。解析 HTML 时,正则表达式为 notoriously bad。
标签: php regex dom preg-match-all domparser