开发者

How to get first and last occurence of an array of words in text using PHP?

$arr = array('superman','gossipgirl',...);


$text = 'arbitary stuff here...';

What I want to do is find the first/last occurencing index of each word in $arr within $text,how to do it e开发者_开发百科fficiently in PHP?


What i think you want is array_keys http://uk3.php.net/manual/en/function.array-keys.php

<?php
$array = array("blue", "red", "green", "blue", "blue");
$keys = array_keys($array, "blue");
print_r($keys);
?>

The above example will output:

Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)

echo 'First '.$keys[0] will echo the first.

You can get the last various ways, one way would be to count the elements and then echo last one e.g.

    $count = count($keys);
    echo ' Last '.$keys[$count -1]; # -1 as count will return the number of entries.

The above example will output:

First 0 Last 4


I think you want:

<?php
$arr = array('superman','gossipgirl',...);
$text = 'arbitary stuff here...';
$occurence_array = array();


foreach ($arr as $value) {
    $first = strpos($text, $value);
    $last = strrpos($text, $value);
    $occurence_array[$value] = array($first,$last);
}
?>


strpos-based methods will tell you nothing about words positions, they only able to find substrings of text. Try regular expressions:

preg_match_all('~\b(?:' . implode('|', $words) . ')\b~', $text, $m, PREG_OFFSET_CAPTURE);
$map = array();
foreach($m[0] as $e) $map[$e[0]][] = $e[1];

this generates a word-position map like this

'word1' => array(pos1, pos2, ...),
'word2' => array(pos1, pos2, ...),

Once you've got this, you can easily find first/last positions by using

$firstPosOfEachWord = array_map('min', $map);


You could do this by using strpos and strrpos together with a simple foreach loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜