php - 如何使用 strpos() 函数查找字符串中多个单词的位置?

标签 php arrays string

我想找到多个单词在字符串中的位置。

例如:

$str="Learning php is fun!";

我想获得 phpfun 的位置。

我的预期输出是:-

1) Php 这个词出现在第 9 位

2) fun 这个词出现在第 16 位。

这是我试过的代码,但它不适用于多个单词。

<?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";

有人知道它出了什么问题以及如何解决吗?

非常感谢任何帮助。

谢谢!

最佳答案

为了补充其他答案,您还可以使用正则表达式:

$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

关于php - 如何使用 strpos() 函数查找字符串中多个单词的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30389724/

相关文章:

java - 从双数组计算统计信息

c# - 字符串解析符 : Can you help me find a way to retrieve this value?

javascript - CodeIgniter 中的重复行

javascript - 如何使用 codeigniter 调用 ajax 中的函数来更新

javascript - 在 woocommerce 感谢页面的 head 标签中插入 javascript 代码

arrays - 梳理hive中表的数据

php - 转换MySQL字段中的二进制(16)数据

python - 快速比较 numpy 数组元素,大于或小于彼此

python - 使 Python RegEx 使用变量作为字符串表达式

c - 如何在C中正确操作字符串