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!
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With