我正在抓取一个站点并获得以下内容:
<input type="BUTTON" value="Geographic Footprint" name="GEO_FOOTPRINT" onclick="return OpenModalDialog('https://mspfast.elavon.com/Symphony/client/client.do?uid=0XrHleUX5MudUYVwwsGDYCl&novaid=5418812&readonly=Y&context=BOARDING&defaultRoute=GeographicFootprint')">
我想要的只是获取uid:0XrHleUX5MudUYVwwsGDYCl
我对regex还很陌生,不太了解它是如何工作的。
我试过做:
'/value="Geographic Footprint" name="GEO_FOOTPRINT" onclick="return OpenModalDialog(''https://mspfast.elavon.com/Symphony/client/client.do?uid=([a-zA-Z0-9]+)'&/'
作为regex,但它不起作用。我得到了unknown modifier '/'
的错误
以下是访问唯一具有name
属性且具有GEO_FOOTPRINT
值的元素的方法:
$html = '<body><input type="BUTTON" value="Geographic Footprint" name="GEO_FOOTPRINT" onclick="return OpenModalDialog(''https://mspfast.elavon.com/Symphony/client/client.do?uid=0XrHleUX5MudUYVwwsGDYCl&novaid=5418812&readonly=Y&context=BOARDING&defaultRoute=GeographicFootprint'')"></body>';
libxml_use_internal_errors(true);
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
$link = $xpath->query('//input[@name="GEO_FOOTPRINT"]')->item(0);
$val = $link->getAttribute('onclick');
现在,一旦我们有了onclick
属性值的文本,我们就可以考虑几种获取uid
值的方法。这里有一个正则表达式:
preg_match('~[?&]uid=([^&'s]+)~', $val, $m);
echo $m[1];
正则表达式[?&]uid=([^&'s]+)
匹配?
或&
,然后是uid
序列,再是=
,然后将除&
或空白('s
)之外的一个或多个字符匹配并捕获到组1中(这样我们就不会交叉其他查询参数)。
可以有其他regexp(您可以在模式的开头添加OpenModalDialog'(''http'S*?
来限制它),或者尝试字符串拆分/子字符串函数等。
请参阅IDEONE演示
下面是一个带有命名组的示例:
$str = "<input type='"BUTTON'" value='"Geographic Footprint'" name='"GEO_FOOTPRINT'" onclick='"return OpenModalDialog('https://mspfast.elavon.com/Symphony/client/client.do?uid=0XrHleUX5MudUYVwwsGDYCl&novaid=5418812&readonly=Y&context=BOARDING&defaultRoute=GeographicFootprint')'">";
$regex = '/uid=(?P<uid>[^&]+)/';
// search for uid literally, afterwards match everything except an ampersand
// and capture it in a group called "uid"
preg_match_all($regex, $str, $matches);
$uid = $matches["uid"][0];
// uid: 0XrHleUX5MudUYVwwsGDYCl
虽然这可能适用于这个特定的示例,但对这些任务使用解析器(例如SimpleXML)几乎是更好的。