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

I want to find the position of a few words in a line.

Example:

$str="Learning php is fun!";

I want to get the position of php and fun .

And my expected result will be: -

1) The word Php was found in the 9th position.

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

Here is the code I tried, but it does not work for a few 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 anyone know what is wrong with him, and how to fix it?

Any help would be very helpful.

Thank!

+4
source share
6 answers

strpos, strpos, fun 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";

:

$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/>";
    }
}

+2

:

$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";
    }
}

: preg_match_all

+3
$str="Learning php is fun!";
$data[]= explode(" ",$str);
print_r($data);//that will show you index

foreach($data as $key => $value){
 if($value==="fun") echo $key;
 if($value==="php") echo $key;
} 

- , 0, , , echo $key+1 ( , ).

+1

:

<?php
$arr_words=array("fun","php");
$str="Learning php is fun!";

foreach($arr_words as $needle) {
    $x = strpos($str, $needle);
    if($x)
        echo "The word '$needle' was found on {$x}th position.<br />";
}
?>
+1

,

strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

.

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

, , .

$arr_words=array("fun","php");
$str="Learning php is fun!";
$x=strpos($str,$arr_words);

$arr_words string, integer

key

$x[1] = strpos($str,$arr_words[0]);
$x[2] = strpos($str,$arr_words[1]);

foreach($arr_words as $key => $value){
     $position = strpos($str,$value);
     echo "The word {$value} was found on {$position}th position"
}
+1
source

You cannot use the strpos function if the second parameter is an array. This is the easiest way:

<?php
     $words = array("php","fun");
     $str = "Learning php is fun!";
     foreach ($words as $word) {
         $pos = strpos($str, $word);
         // Found this word in that string
         if($pos) {
             // Show you message here
         }
     }
+1
source

Source: https://habr.com/ru/post/1589360/


All Articles