Extracting a part of a string is a common task in PHP. You may need to get a username from an email address, shorten a long description, read a file extension, or find a value hidden inside a larger text.
PHP gives you several ways to do this. The right function depends on what you are trying to extract. For fixed positions, substr() is usually enough. For text containing multiple-byte characters, mb_substr() is safer. When the extraction rule is more complex, regular expressions with preg_match() are a better fit.
Choosing the wrong tool is a common developer trap. A regular expression can solve almost anything, but sometimes it is like using a chainsaw to cut a birthday cake. It works, but there is usually a simpler option.
Quick answer: How to extract a string in PHP?
Use the PHP substr() function to extract a portion of a string based on its starting position and length.
<?php
$string = "PHP String Extract";
$result = substr($string, 4, 6);
echo $result;
?>
Output:
String
For multi-byte text such as languages using non-ASCII characters, use mb_substr(). For pattern-based extraction, use preg_match().
PHP string extraction functions
PHP provides different functions for extracting parts of a string. Each one solves a different type of problem.
| Function | Best used for |
|---|---|
substr() |
Extracting characters using position and length |
mb_substr() |
Extracting characters from multi-byte strings |
preg_match() |
Extracting text that matches a pattern |
Before using these functions, it helps to understand how PHP handles string positions. String indexes start from 0, meaning the first character is at position zero.
You can learn more about PHP string handling in the official PHP documentation: PHP string types and operations.
Extract a substring using PHP substr()
The substr() function returns a portion of a string. It accepts the original string, the starting position, and an optional length.
The syntax is:
substr(string, offset, length);
The first two arguments are required. The third argument is optional. If you do not provide the length, PHP returns the remaining part of the string from the starting position.
The official PHP documentation also describes substr() behavior with positive and negative offsets: PHP substr() function reference.
Extract characters from the beginning of a string
<?php
$string = "PHP String Extract";
echo substr($string, 0, 3);
?>
Output:
PHP
Here, the extraction starts at position 0 and returns the first three characters.
Extract characters from the middle of a string
You can start extraction from any position by changing the second argument of substr().
<?php
$string = "PHP String Extract";
echo substr($string, 4, 6);
?>
Output:
String
The extraction starts from position 4 because PHP counts string positions from zero:
P H P _ S t r i n g _ E x t r a c t
0 1 2 3 4 5 6 7 8 9
The underscore character is at position 3, so position 4 starts with the letter S.
Extract the last characters of a string
A negative offset extracts characters from the end of the string. This is useful when you know the value is located at the end, such as a file extension or a code suffix.
<?php
$filename = "report-2026.pdf";
echo substr($filename, -3);
?>
Output:
pdf
The negative offset tells PHP to start counting from the end of the string.
Extract strings with multibyte characters using mb_substr()
The regular substr() function works well for English text and other single-byte character sets. However, it can produce unexpected results when working with languages that use multi-byte characters.
For example, characters in languages such as Japanese, Chinese, and Korean may require more than one byte to store. In these cases, use mb_substr() from the PHP Multibyte String extension.
<?php
$text = "こんにちはPHP";
echo mb_substr($text, 0, 5, "UTF-8");
?>
Output:
こんにちは
The fourth argument specifies the character encoding. For modern applications, UTF-8 is the commonly used choice.
If you are processing user-generated content, names, or international text, using mb_substr() can prevent broken characters appearing in the output.
Extract text using preg_match()
Sometimes the text you want to extract is not located at a fixed position. Instead, you need to find a value that follows a pattern.
For example, extracting a username from an email address is better handled using a regular expression than counting characters.
<?php
$email = "john@example.com";
preg_match('/^(.*?)@/', $email, $matches);
echo $matches[1];
?>
Output:
john
The regular expression captures everything before the @ symbol.
Use preg_match() when the extraction rule depends on the content pattern. Avoid using it for simple position-based extraction because it makes the code harder to read and maintain.
Common mistakes when extracting strings in PHP
Using the wrong starting position
The most common mistake with substr() is forgetting that PHP uses zero-based indexing.
<?php
$text = "Hello PHP";
echo substr($text, 1, 5);
?>
Output:
ello
The first character H is at position 0, not position 1.
Ignoring multibyte characters
Using substr() with UTF-8 text can split characters incorrectly because it works with bytes, not characters.
When handling non-English content, prefer mb_substr() and make sure the Multibyte String extension is enabled.
Using regular expressions for simple extraction
Regular expressions are powerful, but they also increase complexity. If you only need the first few characters or the last part of a string, substr() communicates your intention more clearly.
Practical examples of PHP string extraction
The best way to understand string extraction is to see common situations where developers actually use it.
Extract the file extension
A common task in file upload handling is extracting the extension from a filename.
<?php
$filename = "profile-image.jpg";
$extension = substr($filename, -3);
echo $extension;
?>
Output:
jpg
For real-world applications, especially when validating uploaded files, using PHP’s built-in pathinfo()
function is usually a better approach because it handles filenames more reliably.
Extract a username from an email address
<?php
$email = "developer@example.com";
$username = substr($email, 0, strpos($email, "@"));
echo $username;
?>
Output:
developer
Here, strpos() finds the position of the @ character, and substr() extracts everything before it.
For validating email addresses, avoid manually checking formats with string extraction alone. PHP provides filter_var() with email validation support for that purpose.
Limit a long text for display
A typical use case is showing a short preview of an article or description.
<?php
$description = "PHP provides several useful functions for working with strings.";
$summary = substr($description, 0, 25);
echo $summary . "...";
?>
Output:
PHP provides several useful...
When cutting user-visible text, consider whether you need to avoid splitting words or handle multi-byte characters with mb_substr().
PHP string extraction best practices
- Use
substr()for simple position-based extraction. - Use
mb_substr()when working with UTF-8 or multilingual content. - Use
preg_match()only when extraction depends on a pattern. - Check string length before extracting when input data may be empty or shorter than expected.
- Use dedicated PHP functions when they already solve the problem, such as
pathinfo()for file extensions.
Related PHP string functions
String extraction is usually combined with other PHP string functions. These functions are often used together when processing text:
strlen()to find the length of a string.strpos()to find the position of text inside another string.str_replace()to replace part of a string.- explode() to split a string into an array.
After extracting a string value, you will often need to combine it with other text. See our guide on
PHP string concatenation for examples of joining strings using PHP operators and functions.
Frequently asked questions
How do I extract part of a string in PHP?
Use the substr() function to extract a portion of a string by specifying the starting position and optional length.
How do I extract characters from the end of a string in PHP?
Pass a negative offset to substr(). For example, substr($text, -5) returns the last five characters.
What is the difference between substr() and mb_substr() in PHP?
substr() works with byte positions, while mb_substr() works with characters and is safer for multi-byte text such as UTF-8 content.
Can I extract text using a pattern in PHP?
Yes. Use preg_match() when the text follows a pattern rather than a fixed position.
Conclusion
PHP provides several ways to extract strings, but the right choice depends on the problem. Use substr() for simple position-based extraction, mb_substr() for multilingual text, and preg_match() when you need pattern matching.
Once you understand where each function fits, string extraction becomes a simple and reliable part of everyday PHP development.
This is very use full content.
It’s very helpful for me thanks.
Welcome Vinod