Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the position of multiple words in a string using strpos() function?

Tags:

arrays

string

php

I want to find the position of multiple words in a string.

Forexample :

$str="Learning php is fun!";

I want to get the posion of php and fun .

And my expected output would be :-

1) The word Php was found on 9th position

2) The word fun was found on 16th position.

Here is the code that I tried, but it doesn't work for multiple words.

<?Php
$arr_words=array("fun","php");
$str="Learning php is fun!";
$x=strpos($str,$arr_words);
echo The word $words[1] was found on $x[1] position";
echo The word $words[2] was found on $x[2] position";

Does someone know what's wrong with it and how to fix it?

Any help is greatly appriciated.

Thanks!

like image 712
Amit Verma Avatar asked Jan 08 '23 08:01

Amit Verma


2 Answers

To supplement the other answers, you can also use regular expressions:

$str="Learning php is fun!";

if (preg_match_all('/php|fun/', $str, $matches, PREG_OFFSET_CAPTURE)) {
    foreach ($matches[0] as $match) {
        echo "The word {$match[0]} found on {$match[1]} position\n";
    }
}

See also: preg_match_all

like image 182
Ja͢ck Avatar answered Jan 13 '23 17:01

Ja͢ck


Since you can't load an array of string words inside strpos, you could just invoke strpos twice, one for fun and one for php:

$arr_words = array("fun","php");
$str = "Learning php is fun!";
$x[1] = strpos($str,$arr_words[0]);
$x[2] = strpos($str,$arr_words[1]);
echo "The word $arr_words[0] was found on $x[1] position <br/>";
echo "The word $arr_words[1] was found on $x[2] position";

Sample Output

Or loop the word array:

$arr_words = array("fun","php");
$str = "Learning php is fun!";
foreach ($arr_words as $word) {
    if(($pos = strpos($str, $word)) !== false) {
        echo "The word {$word} was found on {$pos} position <br/>";
    }
}

Sample Output

like image 45
Kevin Avatar answered Jan 13 '23 19:01

Kevin