Home
PHP
Substring Examples
This page was last reviewed on May 18, 2023.
Dot Net Perls
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.
Function arguments. 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.
Substr example. To begin, we invoke the substr function twice. We first declare a string containing the letters "carrot" and then we get parts of it.
Part 1 We take the first 3 characters of "carrot" and place them in a new string. The result is printed with var_dump.
Part 2 We pass a negative argument to substring to get characters from the end of the 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"
Assign index. 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.
Part 1 We access character at index 1. Since strings are 0-based, this is the "b" in "abc."
Part 2 We modify the string by assigning into it. The second character "b" is replaced with a question mark.
Warning If you try to insert more than 1 character by assigning an index, the second and later characters are lost.
// 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"
Substr replace. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 18, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.