繁体   English   中英

如何在html源中的URL中找到关键字,但将链接和锚文本存储在数组中

[英]how to find keyword in URL from html source, but store link and anchor text in array

有点卡住了,我想要做的是循环访问包含指向我站点的链接的URL列表,我正在寻找捕获用于生成链接的HTML代码,或者存储用作链接,

[由marty删除的代码,请参见下文]

因此用于martylinks的代码使用的函数仍在尝试构建,这有点麻烦,但是对于你们来说,我确信它确实很简单。

这是我的find_marty_links函数

function find_marty_links($file, $keyword){
    //1: Find link to my site <a href="http://www.***martin***-gardner.co.uk" target="_blank" title="Web Developer">Web Developer</a>
    //2: copy the FULL HTML LINK to array
    //3: copy the REL value? NOFOLLOW : FOLLOW to array
    //4  copy TITLE (if any) to array
    //5  copy Anchor Text to array

    $htmlDoc = new DomDocument();
    $htmlDoc->loadhtml($file);

    $output_array = array();
    foreach($htmlDoc->getElementsByTagName('a') as $link) {

            // STEP 1
        // SEARCH ENTIRE PAGE FOR KEYWORD?
            // FIND A LINK WITH MY KEYWORD?
            preg_match_all('???', $link, $output); //???//

            if(strpos($output) == $keyword){


               // STEP 2
               // COPY THE FULL HTML FOR THAT LINK?
               $full_html_link = preg_match(??);
               $output_array['link_html'] = $full_html_link;

               // STEP 3
               // COPY THE REL VALUE TO ARRAY
               $link_rel = $link->getAttribute('rel');
               $output_array['link_rel'] = $link_rel;

               // STEP 4
               // COPY TITLE TO ARRAY
               $link_title = $link->getAttribute('title');
               $output_array['link_title'] = $link_title;

               // STEP 5
               // COPY ANCHOR TEXT TO ARRAY
               $anchor_exp = expode('>'); //???
               $anchor_txt = $anchor_exp[2];//??
               $output_array['link_anchor'] = $anchor_txt;

            }

    }
}

!!更新!! 需要产生一个像下面这样的数组

$results = array('link_html' => '<a title="test" href="http://site.com" rel="nofollow">anchor text</a>',
                 'link_rel' => 'nofollow',
                 'link_title' => 'test',
                 'link_anchor' => 'anchor text'
                 )

谢谢大家的帮助。

中号

好的,这是更新的代码:

function find_marty_links($file, $keyword){
    $htmlDoc = new DomDocument();
    $htmlDoc->loadhtml($file);
    $links = array();

    foreach($htmlDoc->getElementsByTagName('a') as $link) {
        $url = $link->getAttribute('href');
        $title = $link->getAttribute('title');
        $text = $link->nodeValue;
        $rel = $link->getAttribute('rel');

        if(strpos($url,$keyword) !== false || strpos($title,$keyword) !== false || strpos($text,$keyword) !== false)
        {
            $links[] = array('url' => $url, 'text' => $text, 'title' => $title, 'rel' => $rel);
        }
    }

    return $links;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM