Gtker
Gtker

Reputation: 2257

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

Upvotes: 0

Views: 1593

Answers (4)

lugte098
lugte098

Reputation: 2309

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);
}
?>

Upvotes: 3

user187291
user187291

Reputation: 53940

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);

Upvotes: 1

Jens
Jens

Reputation: 25573

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

Upvotes: 0

Lizard
Lizard

Reputation: 45012

What i think you want is array_keys https://www.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

Upvotes: 4

Related Questions