We have a variable $string, its contains some text like:
About 200 million CAPTCHAs are solved by humans around the world every day.
How can we get 2-3 last or first letters of each word (which length is more than 3 letters)?
Will check them for matched text with foreach():
if ('ey' is matched in the end of some word) {
replace 'ey' with 'ei' in this word;
}
Thanks.
First, I’ll give you an example of how to loop through a string and work with each word in the string.
Second, I’ll explain each part of the code so that you can modify it to your exact needs.
Here is how to switch out the last 2 letters (if they are “ey”) of each word that is more than 3 letters long.
Live example
I’ll explain each function so that you can modify the above to exactly how you want it, since I don’t precisely understand all your specifications:
explode(" ", $string)will split$stringby the use of spaces. The spaces will not be included in the array.foreach($string as $key => $word)will go through each element of$stringand for each element it will assign the index number to$keyand the value of the element (the word in this case) to$word.substr($word, -2)returns the substring that begins two from the end of the string and goes to the end of the string…. the last two letters. If you want the first two letters, you would usesubstr($word, 0, 2), since you’re starting at the very beginning and want a length of 2 letters.substr_replace($word, $switchTo, -2)will take$wordand starting at the penultimate letter, replace what’s there with$switchTo. In this case, we’ll switch out the last two letter. If you want to replace the first two letters, you would usesubstr_replace($word, $switchTo, 0, 2)