views:

57

answers:

4
$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 efficiently in PHP?

+2  A: 

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
Lizard
This is not what I want,you didn't even used `$text`..
Gtker
A: 

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

Jens
Is there a built-in function like `strpos` and `strrpos` but takes an array of words for input?
Gtker
@Runner: None that I know of, but that does not mean much. =)
Jens
+1  A: 

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);
stereofrog
+2  A: 

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);
}
?>
lugte098
So there is no built-in function like `strpos` and `strrpos` but takes an array of words for input?
Gtker
no, you have to do it like this (or something similar). You could always write a function yourself that can do exactly what you want of course. This is not a very difficult or large pieze of code.
lugte098