Home Backend Development PHP Tutorial PHP 抽取网页题目并剔除不相关的seo关键字

PHP 抽取网页题目并剔除不相关的seo关键字

Jun 13, 2016 pm 01:04 PM
title

PHP 抽取网页标题并剔除不相关的seo关键字
场景描述:

  过往我们在抽取网页标题的时候,都会直接抽取 之间的内容. 但实际情况是这样,例如javaeye 的一篇文章 http://www.iteye.com/news/21643 ,  的内容为 "10年软件开发教会我最重要的10件事 - 非技术 - ITeye资讯", 但实际引用中我们期望的标题应该为 "10年软件开发教会我最重要的10件事". 所以标题后面堆砌了很多不相关的关键字(应该是为了  seo 吧). 所以我们希望过滤掉这些关键字. 有下面的方法可以参考:


1. 查找 h1 等标签.(分析sina news 一些网站之后, 觉得不可行,会有很多干扰)

2. 从全文去标题后,将 之间的内容切割(按 _ | -)为 a1,a2,a3,a4,然后从最长的词组a3开始从全文查找. 如果查找成功,那么开始向左边迭代查询 a2,a1,直到查询失败为止 。左侧失败后,再继续向右迭代,同理. (这里我采用的是这种方法)


<?php /**
 * @author pqcc <struts.ec@mgail.com>
 * @date: 2011-06-18
 * Description: 给定一个网页内容,提取网页的标题. 提取的标题不包括 seo 关键字.
 * e.g: 一篇新闻标题的从<title>直接抽取结果为 "大学英语四六级本周六开考 909万人参考_新浪教育_新浪网",
 *       但我们希望的结果是:"大学英语四六级本周六开考 909万人参考".
 * 适用范围:  文章最终页标题的提取, 不包括专题页等.
 */

class TitlePurify{

    private $matches_preg = '[-_\s|―]';

    function getTitle($contents){/*{{{*/
        $preg = "/<title>]*>([\w|\t|\r|\W]*?)/i";
        preg_match($preg, $contents, $matches);
        if(count($matches)trimTitle($title, $contents);
    }/*}}}*/

    function trimMeta($contents){/*{{{*/
        // 首先去除 <title> 内容, <meta> 内容.
        $preg       = "/<title>]*>([\w|\t|\r|\W]*?)/i";
        $contents   = preg_replace($preg, '', $contents);
        $preg       = "/<meta>]*>/i";
        $contents   = preg_replace($preg, '', $contents);
        return $contents;
    }/*}}}*/


    // 获取长度最长的 item?所处的index.
    function getMaxIndex($titles){/*{{{*/
        $maxItemIndex   = 0;
        $maxLength      = 0;
        $loop           = 0;
        foreach($titles as $item){
            if(strlen($item)>$maxLength){
                $maxLength      = strlen($item);
                $maxItemIndex   = $loop;
            }        
            $loop++;
        }
        return $maxItemIndex;
    }/*}}}*/

    function trim($title, $titles, $contents, $maxItemIndex){/*{{{*/
        //@todo : 此处可优化contents
        // 如果查找成功. result = tempTitle. 
        $tempTitle  = $titles[$maxItemIndex];
        $result     = $tempTitle;
        $count      = count($titles);
        // while 从当前index 向左进行迭代(直到到达第一个或者匹配失败才中止).
        $leftIndex  = $maxItemIndex-1;
        while(true && $leftIndex>=0){
            // tempTitle+左一个.
            preg_match("/({$this->matches_preg}+{$tempTitle})/i", $title, $matches);
            if(count($matches)>1){
                // temp 用于匹配失败后,进行回滚.
                $temp       = $titles[$leftIndex] . $matches[1];
                $tempTitle  = $titles[$leftIndex] . $matches[1];
                // 继续拿着 tempTitle 去匹配.
                preg_match("/$tempTitle/i", $contents, $matches);
                // 如果查找失败....
                if(count($matches)matches_preg}+)/i", $title, $matches);
            if(count($matches)>1){
                // temp 用于匹配失败后,进行回滚.
                $temp       =  $matches[1] . $titles[$rightIndex];
                $tempTitle  =  $matches[1] . $titles[$rightIndex];
                // 继续拿着 tempTitle 去匹配.
                preg_match("/$tempTitle/i", $contents, $matches);
                // 如果查找失败....
                if(count($matches)trimMeta($contents);    
        // 配置切割标题的规则.
        $titles = preg_split("/$this->matches_preg/i", $title);
        $count          = count($titles);
        //var_dump($titles);exit;

        // 将当前最长的 item 从全文查找.
        $maxItemIndex = $this->getMaxIndex($titles);
        $tempTitle   = $titles[$maxItemIndex];
        preg_match("/$tempTitle/i", $contents, $matches);
        // 如果查找失败....
        if(count($matches)trim($title, $titles, $contents, $maxItemIndex);
    }/*}}}*/

}

// -------------   test code ------------------------------
function convertEncoding($contents){
    preg_match("/charset=([\w|\-]+);?/i", $contents, $match);
    $charset = isset($match[1])? $match[1] : 'UTF-8';
    $contents = mb_convert_encoding($contents, 'UTF-8', $charset);
    return $contents;
}

$url = 'http://china.nba.com/news/4/2011/0617/61383331/10451.html';
$contents = file_get_contents($url);
$contents = convertEncoding($contents);

$startTime  = microtime();
$purify     = new TitlePurify();
$title      = $purify->getTitle($contents);
$endTime    = microtime();

echo "标题:        $title ";
echo "cost: " . ($endTime-$startTime);

?>

</title>
</title>
</title>
</title>
Copy after login



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? Apr 01, 2025 pm 03:09 PM

An official introduction to the non-blocking feature of ReactPHP in-depth interpretation of ReactPHP's non-blocking feature has aroused many developers' questions: "ReactPHPisnon-blockingbydefault...

See all articles