gpt4 book ai didi

php 正则表达式可选择匹配整个单词

转载 作者:可可西里 更新时间:2023-10-31 23:34:29 24 4
gpt4 key购买 nike

我正在使用 php,我需要从对网站的一些 curl 响应中抓取一些信息。我正在模拟浏览器的 ajax 请求和浏览器的正常(整个)页面请求,但是 ajax 响应与 html 的这一部分中的整个页面请求略有不同。

ajax 响应是: <div id="accountProfile"><h2>THIS IS THE BIT I WANT</h2><dl id="accountProfileData">

然而正常的 react 是: <div id="accountProfile"><html xmlns="http://www.w3.org/1999/xhtml"><h2>THIS IS THE BIT I WANT</h2><dl id="accountProfileData">

即 ajax 响应缺少标记:<html xmlns="http://www.w3.org/1999/xhtml"> .我需要得到 h2 之间的位标签。显然我不能只抓取 <h2>THIS IS THE BIT I WANT</h2><dl id="accountProfileData"> 的页面因为这些标签可能出现在其他地方并且不包含我想要的信息。

我可以单独匹配其中一种模式,但我想在一个正则表达式中同时进行这两种模式。这是我匹配 ajax 响应的解决方案:

<?php
$pattern = '/\<div id="accountProfile"\>\<h2\>(.+?)\<\/h2\>\<dl id="accountProfileData"\>/';
preg_match($pattern, $haystack, $matches);
print_r($matches);
?>

谁能告诉我应该如何更改模式以选择性地匹配 <html xmlns="http://www.w3.org/1999/xhtml">标签也是?如果它有助于为了简洁的目的简化干草堆,那很好。

最佳答案

我还没有测试过,但你可以试试这个:

    $pattern = '/\<div id="accountProfile"\>(\<html xmlns=\"http://www.w3.org/1999/xhtml\"\>){0,1}\<h2\>(.+?)\<\/h2\>\<dl id="accountProfileData"\>/';

关于php 正则表达式可选择匹配整个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5946712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com