Common PHP String Manipulation Functions and Examples
This article explains several essential PHP string functions—including substr, mb_substr, stripos with substr, and direct character indexing—providing clear code examples and output demonstrations for handling both ASCII and multibyte characters.
PHP string functions are a core part of the language, and this guide covers the most commonly used methods for extracting substrings.
1. substr() extracts a portion of a string based on start position and length.
";
echo substr($str,2,4); // rave
echo "
";
echo substr($str,-3); // vel
?>The outputs are avel , rave , and vel respectively.
2. mb_substr() handles multibyte characters such as Chinese, requiring the php_mbstring extension.
Output: 内 .
To obtain the part of a string before a certain number of characters, calculate the total length and subtract the desired offset:
Result: 文 .
3. Using stripos() with substr() to locate a character and extract substrings to the left or right of it.
";
echo substr("abcde", 0, stripos("abcde", "c")); // ab
?>Outputs are cde and ab .
4. Direct character access by index using array syntax.
Output: a .
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.