Strings in Depth
String checks answer true or false questions about the start, the end, and the inside of a string. Split and join functions turn one string into an array of parts and back again.
Three checks on one word
The word notebook holds book inside it and starts with note. It does not end with pen, so the three bool answers read true, true, false.
<?php
$word = "notebook";
var_dump(str_contains($word, "book"));
var_dump(str_starts_with($word, "note"));
var_dump(str_ends_with($word, "pen"));explode splits a line into parts
The separator here is a comma. Each comma marks a split, and the three parts come back as an array.
<?php
$line = "pen,book,bag";
$parts = explode(",", $line);
print_r($parts);implode joins parts back with a glue
The glue here is a dash with a space on each side. The three parts join into one line with the glue between them.
<?php
$parts = ["pen", "book", "bag"];
$line = implode(" - ", $parts);
echo $line . "\n";str_repeat builds a divider
The dash repeats twelve times to make one divider line. The same line prints above and below the text.
<?php
echo str_repeat("-", 12) . "\n";
echo "Sale starts\n";
echo str_repeat("-", 12) . "\n";Example
<?php
$email = "hana@example.com";
$parts = explode("@", $email);
print_r($parts);
var_dump(str_ends_with($email, ".com"));
$rebuilt = implode("@", $parts);
echo $rebuilt . "\n";Key points
- str_contains answers true when a piece of text sits anywhere inside a string.
- str_starts_with answers true when a string begins with a given piece of text.
- str_ends_with answers true when a string ends with a given piece of text.
- Each of the three checks hands back a bool, so var_dump shows the answer and its type in one line.
- explode splits a string into an array of parts at each place a separator appears.
- implode joins the values of an array into one string with a glue text between them.
- str_repeat builds a string by writing the same text a set number of times.
In this example, an email address is taken apart and rebuilt. explode splits the address at the @ sign into the name hana and the domain example.com. str_ends_with then checks the ending of the address and answers true for .com. implode joins the two parts with an @ sign, and the rebuilt address prints whole again.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does explode(",", "a,b,c") hand back?