counting 10 characters back from the end and then taking the next 4
characters forward:
Click here to view code image
echo substr($ourstring, -10, 4);
Finally, you can use a negative third parameter, too, which also counts back
from the end of the string. For example, using “-4” as the third parameter
means to take everything except the last four characters. Confused yet? This
code example should make it clear:
Click here to view code image
echo substr($ourstring, -19, -11);
This counts 19 characters backward from the end of the string (which places it
at the O in Over) and then copies everything from there until 11 characters
before the end of the string. That prints Over The. You could write the
same thing using – 19 and 8 , or even 29 and 8 ; there is more than one way to
do it.
Moving on, the strpos() function returns the position of a particular
substring inside a string; however, it is most commonly used to answer the
question, “Does this string contain a specific substring?” You need to pass
two parameters to it: a haystack and a needle. (Yes, that’s a different order
from str_replace().)
In its most basic use, strpos() can find the first instance of Box in your
phrase, like this:
Click here to view code image
echo strpos($ourstring, "Box");
This outputs 18 because that is where the B in Box starts. If strpos()
cannot find the substring in the parent string, it returns false rather than the
position. Much more helpful, though, is the ability to check whether a string
contains a substring; a first attempt to check whether your string contains the
word The might look like this:
Click here to view code image
<?php
$ourstring = "The Quick Brown Box Jumped Over The Lazy Dog";
if (strpos($ourstring, "The")) {
echo "Found 'The'!\n";
} else {
echo "'The' not found!\n";
}
?>