【问题标题】:find pattern for url with no ending slash查找没有结尾斜杠的 url 模式
【发布时间】:2013-03-14 16:30:08
【问题描述】:

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

例如:如果我有

  1. a href="/testing/abc/">以斜线结尾

  2. a href="/testing/test/mnl">无结束斜线

结果将是#2

谢谢。

【问题讨论】:

  • 你怎么知道某事是一个 URL?
  • preg_match_all('#a href="([^"]*[^/])"#i')

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


【解决方案1】:

最好使用 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)

【讨论】:

  • 它有效!能否请您简要解释一下。非常感谢
  • 我正在尝试获取所有没有尾部斜杠的 href 链接,但排除其中包含“图像”文本/路径或 .pdf 的链接。我试过正则表达式看看后面但没有成功。感谢您的建议。
  • 既然这看起来像是一个新要求,请您创建一个问题,我很乐意提供答案。
  • 哦,谢谢,好像有人回答了你的问题。如果这不能解决您的问题,请告诉我,然后我也可以为您找到一个正则表达式。
【解决方案2】:

确实,使用 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 );

【讨论】:

    猜你喜欢
    • 2010-10-02
    • 1970-01-01
    • 2017-12-02
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多