preg_split regex help - PullRequest
       4

preg_split regex help

0 голосов
/ 14 августа 2011

В приведенной ниже функции processPage я извлекаю ключевые слова из метатега ключевых слов каждого обработанного URL.Мне нужно изменить preg_split так, чтобы он вытягивал только первые три слова из любого кластера ключевых слов.

Например, для данного ключевого слова meta tag:

<meta name="keywords" content="this is too long, this is not, keyword three" />

I onlyхочу, чтобы это было тоже частью первого кластера ключевых слов.

Кроме того, если общий список ключевых фраз длиннее 10, я хочу извлечь только первые 10 ключевых фраз из списка.

т.е. (ключевая фраза 1, квт 2, квт 3, квт4 и т. Д., Ключевая фраза 10)

Любая помощь очень ценится.

<?php

class ResultPage
{
    function __construct($siteurl){$this->url = $siteurl;$this->processPage();}

    public $url;
    public $title;
    public $html;
    public $plainText;
    public $wordList;
    public $keywords = array();

    function processPage(){
        $this->html = rseo_keywordSearch_scrapePage($this->url);
        $dom = str_get_html($this->html);
        $metakws = $dom->find('meta[name=keywords]');
        if(count($metakws)){
            $metakw = $metakws[0];
            if($metakw->content){
                $this->keywords = preg_split("/[\s]*[,][\s]*/",$metakw->content); //EDIT HERE
                }
            }
        }

    public function GetResults(){
        return rseo_keyword_getCountArray($this->wordList);
    }
}


/*
 * 
 * Calls remote web page using cUrl, 
 * and returns the raw html
 * 
 */
function rseo_keywordSearch_scrapePage($url, $headonly = TRUE ){

    $agents = 'Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.204 Safari/534.16';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_VERBOSE, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_USERAGENT, $agents);
    //curl_setopt($ch, CURLOPT_NOBODY, $headonly);
    curl_setopt($ch, CURLOPT_URL, $url);

    $curlResp = curl_exec($ch);
    curl_close($ch);
    $resp = str_replace("class=l","class='l'",$curlResp);

    return $resp;
}

function rseo_keyword_getCountArray($arr){
    $retarr = array_count_values($arr);
    arsort($retarr);
    return $retarr;
}

Ответы [ 2 ]

1 голос
/ 14 августа 2011

Сравнение немного проще, чем разделение, например:

preg_match_all('/(?<=^|,)\s*((?:[^\s,]+\s*){1,3})/', $metakw->content, $m);
$this->keywords = array_slice($m[1], 0, 10);

print_r($this->keywords);

/*
Array
    (
        [0] => this is too 
        [1] => this is not
        [2] => keyword three
    )
*/
0 голосов
/ 14 августа 2011

Preg_split не идеален для того, что вы пытаетесь сделать.

Я бы попробовал что-то вроде этого:

$keywords = explode(',', $this->content);

foreach ($keywords as $key => $keyword) {
    $count = substr_count($keyword, ' ');

    if ($count > 2) {
        // first 3 words out of a keyword cluster.
        $this->keywords[] = implode(' ', explode(' ', $keyword, -($count - 2)));
    } else {
        $this->keywords[] = $keyword;
    }

    // stop a 10 keywords
    if ($key + 1 == 10) {
        break;
    }
}
...