Reputation: 4862
Is there a way to find all instances of a substring in a string. This is what I have so far but it seems when I search for the 'ed' substring it stops looking when it finds the first one. Thus, the word 'hedged' is unaffected when I try to alter the ending.
<?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);
}
}
}
?>
This is the output I get. I basically want a way to make the programme alter the ending of 'hedged'. Thanks.
Array
(
[kissed] => Array
(
[0] => kisst
)
[hoped] => Array
(
[0] => hopt
)
[learned] => Array
(
[0] => learnd
)
[wanted] => Array
(
[0] => wantid
)
[sounded] => Array
(
[0] => soundid
)
[hedged] => Array
(
)
)
Upvotes: 0
Views: 92
Reputation: 4862
I just altered the opening IF condition and adjusted the $pos variable:
if((strlen($wordList2[$i]) - strrpos($wordList2[$i], 'ed'))===2) {
$pos = strrpos($wordList2[$i], 'ed');
...etc.
Works much better now, thanks moopet.
Upvotes: 0
Reputation: 6175
For your specific requirement you could use strrpos instead of strpos - it's the same thing except it finds the last occurrence of the substring rather than the first.
Upvotes: 1