php · level 2 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Ask a string what is inside it, and where.
gives true when the second string appears anywhere in the first. str_starts_with and str_ends_with check only the start or the end. All three care about capital letters.
tells you where. It gives a , counting from 0 like an array index, or false when the text is not there. Careful: a match at the very start gives 0, so always compare with !== false.
cuts out 5 characters starting at position 0. A negative start counts from the end, so substr($file, -3) gives the last three.
<?php
$email = "mia@example.com";
if (str_contains($email, "@")) {
echo "Looks like an email\n";
}
$at = strpos($email, "@");
echo "The @ is at position $at\n";
echo "Name: " . substr($email, 0, $at) . "\n";
echo "Ends: " . substr($email, -3) . "\n";
if (str_ends_with($email, ".com")) {
echo "A .com address\n";
} Leave out the length, as in substr($email, 4), and you get everything to the end.
guess first
Search a song title. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$song = "Here comes the sun";
echo strpos($song, "sun") . "\n";
echo substr($song, 5, 5) . "\n";
your turn
Your turn. Spot the photos.
Type a file name, like beach.jpg or notes.txt, then run it. Try one of each.
fix it
This parcel came from Britain. Can you fix the check?
- GB is right there. What position does
strposgive for text at the very start? - It gives 0, and
iftreats 0 likefalse. Ask whether the answer is notfalseinstead. - Change line 3 to
if (strpos($code, "GB") !== false) {, then press run.
nailed it
you can find anything inside a string. :D
str_contains,str_starts_withandstr_ends_withgivetrueorfalse.strposgives a position orfalse, so use!== false.substrcuts out part of a string.
new words in your collection
- str_contains
- position
- strpos
- substr
This lesson isn’t saved. A free account remembers every lesson you finish.