找到没有结束斜杠的网址的模式

时间:2013-03-14 16:30:08

标签: php preg-match-all regex-negation

我正在寻找preg_match_all模式来查找页面上没有尾部斜杠的所有网址。

例如:如果我有

  1. a href =“/ testing / abc /”>以斜杠结尾

  2. a href =“/ testing / test / mnl”>没有结束斜杠

  3. 结果将是#2

    感谢。

2 个答案:

答案 0 :(得分:0)

使用DOM解析器更好地提取所有href链接,并查看URL是否以斜杠结尾。没有正则表达式。

对于所提供示例的正则表达式解决方案,您可以使用此正则表达式:

/href=(['"])[^\s]+(?<!\/)\1/

现场演示:http://www.rubular.com/r/f2XJ6rF5Fb

说明:

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 );
相关问题