是否有方法在字符串中查找子字符串的所有实例。到目前为止,这就是我所拥有的,但当我搜索"ed"子字符串时,当它找到第一个子字符串时,它似乎停止了搜索。因此,当我试图改变结尾时,"对冲"一词不受影响。
<?php
$wordList2 = array('kissed','hoped','learned','wanted','sounded', 'hedged');
for ($i = 0; $i<sizeof($wordList2);$i++){
$wrongAnswers2[$wordList2[$i]] = array();
}
for ($i = 0; $i < sizeof($wordList2); $i++){
if(strpos($wordList2[$i], 'ed')===(strlen($wordList2[$i])-2)) {
$pos = strpos($wordList2[$i], 'ed');
if(
substr($wordList2[$i], -3, 1) ==='p' ||
substr($wordList2[$i], -3, 1) ==='f' ||
substr($wordList2[$i], -3, 1) ==='s' ||
substr($wordList2[$i], -3, 1) ==='k' ||
substr($wordList2[$i], -3, 1) ==='h'
){
$replacement = substr_replace($wordList2[$i], 't', $pos,2);
array_push($wrongAnswers2[$wordList2[$i]],$replacement);
} else if
(
substr($wordList2[$i], -3, 1) ==='b' ||
substr($wordList2[$i], -3, 1) ==='v' ||
substr($wordList2[$i], -3, 1) ==='z' ||
substr($wordList2[$i], -3, 1) ==='g' ||
substr($wordList2[$i], -3, 1) ==='n'
){
$replacement = substr_replace($wordList2[$i], 'd', $pos,2);
array_push($wrongAnswers2[$wordList2[$i]],$replacement);
} else if
(
substr($wordList2[$i], -3, 1) ==='d' ||
substr($wordList2[$i], -3, 1) ==='t'
){
$replacement = substr_replace($wordList2[$i], 'id', $pos);
array_push($wrongAnswers2[$wordList2[$i]],$replacement);
}
}
}
?>
这是我得到的输出。我基本上想要一种方法,使程序改变"对冲"的结束。谢谢
Array
(
[kissed] => Array
(
[0] => kisst
)
[hoped] => Array
(
[0] => hopt
)
[learned] => Array
(
[0] => learnd
)
[wanted] => Array
(
[0] => wantid
)
[sounded] => Array
(
[0] => soundid
)
[hedged] => Array
(
)
)
对于您的特定需求,您可以使用strrpos而不是strpos-这是一样的,只是它能找到子字符串的最后一个而不是第一个。
我刚刚更改了打开IF条件并调整了$pos变量:
if((strlen($wordList2[$i]) - strrpos($wordList2[$i], 'ed'))===2) {
$pos = strrpos($wordList2[$i], 'ed');
...etc.
现在效果好多了,谢谢moopet。