我想找到多个单词在字符串中的位置。
例如:
$str="Learning php is fun!";
我想获得 php 和 fun 的位置。
我的预期输出是:-
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/