Substring
In PHP programs we often need to access just a part of a string
, not the entire string
. Consider the word "substring": we can just access the "string
" part of it.
The PHP substr function receives the source string
, the offset index (0-based) and a length. We must pass a length, not the end index.
To begin, we invoke the substr function twice. We first declare a string
containing the letters "carrot" and then we get parts of it.
string
. The result is printed with var_dump
.string
.$word = "carrot"; // Part 1: get first 3 characters. $result1 = substr($word, 0, 3); var_dump($result1); // Part 2: get last 3 characters. $result2 = substr($word, -3); var_dump($result2);string(3) "car" string(3) "rot"
We can modify a string
in PHP by assigning into it. When we assign a character by index, we can only place one new character there.
string
by assigning into it. The second character "b" is replaced with a question mark.// Part 1: get character from string. $input = "abc"; $second = $input[1]; var_dump($second); // Part 2: change character in string. $input[1] = "?"; var_dump($input);string(1) "b" string(3) "a?c"
This method changes a range of characters in the input string. So we specify a start index, and a length, and that part of the string
is replaced with something else.
// The input string. $input = "abc abc"; // Replace chars starting at index 1 and continuing for 2 chars. $result = substr_replace($input, "??", 1, 2); var_dump($result);string(7) "a?? abc"
Taking substrings in PHP is common—nearly every PHP program in the real world does this. For 1-character substrings, we can use an index expression.