English 中文(简体)
Parse All Links that Contain A specific Word in "href” Tag [duplicate]
原标题:Parse All Links That Contain A Specific Word In "href" Tag [duplicate]
  • 时间:2011-11-21 06:51:27
  •  标签:
  • php
  • parsing
This question already has answers here:
Closed 10 years ago.

Possible Duplicate:
Grabbing the href attribute of an A element

我需要把包含一些字句的超文本文件的所有链接(始终不一样)。

例:

<a href="/bla:bla">BLA</a>
<a href="/link:link">BLA</a>
<a href="/link:bla">BLA</a>

我只需要与“href=/link:......”的联系。

$html = "SOME HTLM ";
$dom = new DomDocument();
@$dom->loadHTML($html);
$urls = $dom->getElementsByTagName( a );
foreach ($urls as $url)
{
    echo "<br> {$url->getAttribute( href )} , {$url->getAttribute( title )}";
    echo "<hr><br>";
}

在这个例子中,我需要具体的联系。

最佳回答

By using a condition.

<?php 
$lookfor= /link: ;

foreach ($urls as $url){
    if(substr($url->getAttribute( href ),0,strlen($lookfor))==$lookfor){
        echo "<br> ".$url->getAttribute( href )." , ".$url->getAttribute( title );
        echo "<hr><br>";
    }
}
?>
问题回答

不要先点所有内容,然后过滤你所需要的内容,你可以直接通过:

//a[contains(@href, "link:")]

将在contain的文件中找到所有内容>。 The string link: in the hrefvide

检查母子(starts with 链接:你可以做些什么。

//a[starts-with(@href, "link:")]

Full example (demo):

$dom = new DomDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
foreach ($xpath->query( //a[contains(@href, "link:")] ) as $a) {
    echo $a->getAttribute( href ), PHP_EOL;
}

也请见

关于相关问题。

说明:由于许多相关问题,标识这一化学武器:

使用定期表述。

foreach ($urls as $url)
{
    $href = $url->getAttribute( href );
    if (preg_match("/^/link:/",$href){
        $links[$url->getAttribute( title )] = $href;
    }
}

链接阵列中包含所有与之相匹配的标题和手法。

既然只是让大家回来,那么你只需要检查一下从表面上开始的情况。

$href = $url -> getAttrubute ( href );
if (strpos ($href,  /link: ) === 0)
{
    // Do your processing here
}




相关问题
Parse players currently in lobby

I m attempting to write a bash script to parse out the following log file and give me a list of CURRENT players in the room (so ignoring players that left, but including players that may have rejoined)...

How to get instance from string in C#?

Is it possible to get the property of a class from string and then set a value? Example: string s = "label1.text"; string value = "new value"; label1.text = value; <--and some code that makes ...

XML DOM parsing br tag

I need to parse a xml string to obtain the xml DOM, the problem I m facing is with the self closing html tag like <br /> giving me the error of Tag mismatch expected </br>. I m aware this ...

Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

Locating specific string and capturing data following it

I built a site a long time ago and now I want to place the data into a database without copying and pasting the 400+ pages that it has grown to so that I can make the site database driven. My site ...

热门标签