我正在寻找preg_match_all模式来查找页面上没有尾部斜杠的所有网址。
例如:如果我有
a href =“/ testing / abc /”>以斜杠结尾
a href =“/ testing / test / mnl”>没有结束斜杠
结果将是#2
感谢。
答案 0 :(得分:0)
使用DOM解析器更好地提取所有href链接,并查看URL是否以斜杠结尾。没有正则表达式。
对于所提供示例的正则表达式解决方案,您可以使用此正则表达式:
/href=(['"])[^\s]+(?<!\/)\1/
href= -> match text href=
(['"]) -> match single or double quote and create a group #1 with this match
[^\s]+ -> match 1 or more character until a space is found
(?<!\/) -> (negative lookbehind) only match if is not preceded by /
\1 -> match closing single or double quote (group #1)
答案 1 :(得分:0)
确实,使用DOM解析器 [why?] 。这是一个例子:
// let's define some HTML
$html = <<<'HTML'
<html>
<head>
</head>
<body>
<a href="/testing/abc/">end with slash</a>
<a href="/testing/test/mnl">no ending slash</a>
</body>
</html>
HTML;
// create a DOMDocument instance (a DOM parser)
$dom = new DOMDocument();
// load the HTML
$dom->loadHTML( $html );
// create a DOMXPath instance, to query the DOM
$xpath = new DOMXPath( $dom );
// find all nodes containing an href attribute, and return the attribute node
$linkNodes = $xpath->query( '//*[@href]/@href' );
// initialize a result array
$result = array();
// iterate all found attribute nodes
foreach( $linkNodes as $linkNode )
{
// does its value not end with a forward slash?
if( substr( $linkNode->value, -1 ) !== '/' )
{
// add the attribute value to the result array
$result[] = $linkNode->value;
}
}
// let's look at the result
var_dump( $result );