Extract a substring from a string in PHP
echo substr('This is my text', 2, 5); // is is
Use the PHP built-in substr()
function to extract a substring from a string. The syntax looks like this:
substr(string $string, int $offset, ?int $length = null): string
The first two parameters are mandatory. The $length
is optional. If you do not specify the $length
parameter, it will go to the end of the string automatically. So without $length
, you cut the beginning of a string, while if you specify a value you cut the beginning and the end.
Handling international text
It is important to know that the substr
function only works correctly for normal ASCII characters. If you want to use it on international texts, it will give wrong results for strings containing special multibyte characters. For example:
echo substr("Programacion PHP", 12); // PHP
echo substr("Programación PHP", 12); // n PHP
Fortunately, there is a built-in solution for this. You should use the multibyte version of the function mb_substr
:
echo mb_substr("Programación PHP", 12); // PHP
You should also know that to handle multibyte strings, you need to enable the mbstring
extension in php.ini
: extension=mbstring
- Remove whitespace from the beginning and end of a string in PHP
- Locate a substring within a string in PHP
- Process CSV line in PHP
- Extract a substring from a string in PHP
- Split a string into words in PHP
- Replace spaces with dashes in PHP
- Replace only the first occurrence of a string in PHP
- Replace last occurrence of a string in a string in PHP
- Remove all attributes from HTML tags in PHP
- Remove HTML tags from a string except p, b, i and br in PHP
- Remove HTML tags from a string in PHP