我想在字符串中找到多个单词的位置。
例如:
$str="Learning php is fun!";
我想获得 php 和 fun 的位置。
我的预期输出是: -
1)在第9个位置找到 Php 这个词
2)在第16位发现了 fun 这个词。
以下是我尝试过的代码,但它不适用于多个单词。
<?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";
有人知道它有什么问题以及如何解决它?
任何帮助都非常适合。
谢谢!
答案 0 :(得分:3)
要补充其他答案,您还可以使用正则表达式:
$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
答案 1 :(得分:2)
由于您无法在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 :(得分:1)
$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;
}
Key是确切的位置,但索引从0开始,所以请记住相应地修改你的代码,可能是echo $key+1
(多种方式,取决于你)。
答案 3 :(得分: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 />";
}
?>
答案 4 :(得分: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.
<强>偏移强> 如果指定,搜索将从字符串的开头开始计算此字符数。
参考Docs
在你的例子中
$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"
}
答案 5 :(得分:1)
如果第二个参数是一个数组,则不能使用函数 strpos 。 这是最简单的方法:
<?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
}
}