- Instant help with your Php coding problems

Extract a substring from a string in PHP

How to 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



Share "How to extract a substring from a string in PHP?"
Interesting things
ChatGPT in a nutshell