PHP substr Function: How to Extract and Manipulate Strings

php substr function

The substr() function in PHP returns part of a string. You give it a string, a starting point, and optionally a length. It cuts the string based on those numbers and gives you the piece you asked for.

Understand the substr Function in PHP

You use substr() when you need to pull out a part of a string. Maybe you want just the first few letters. Maybe you need everything after a certain point. It works well when you know the position of the part you want.

Here is the full syntax for substr():

substr(string $string, int $start, ?int $length = null): string

Here, what each part does.

  • $string
    This is the full string you want to work with. It can be any string.
  • $start
    This tells PHP where to start cutting. The count starts from 0. If you use a negative number, PHP counts from the end of the string.
  • $length (optional)
    This tells PHP how many characters to return. If you leave it out, PHP gives you everything from the start point to the end of the string. If the number is negative, PHP will stop that many characters from the end.

A Quick example:

$text = "Welcome to flatcoding tutorials";
echo substr($text, 0, 7); 

Output:

Welcome

PHP starts at index 0 and returns the next 7 characters.

You can also use a negative start value:

echo substr($text, -20);

This starts 20 characters from the end and goes to the end of the string. Its output:

flatcoding tutorials

Examples of the substr Function in PHP

Multibyte strings:

If you work with non-English characters like Japanese, Arabic, or emojis, substr() might not work correctly. That is because substr() counts bytes, not full characters.

$text = "こんにちは"; // Japanese
echo substr($text, 0, 3); // Broken output: こ

This function works on standard strings. For multibyte support, see other PHP functions.

Mix substr() with another string:

You can mix substr() with other string functions. Here is an example:

$email = "user@example.com";
$domain = substr(strrchr($email, "@"), 1);
echo $domain; 

The output:

example.com

This first finds the @ and then cuts the domain part.

Extracting file extensions:

You can get a file extension like this:

$file = "photo.jpg";
$ext = substr($file, strrpos($file, '.') + 1);
echo $ext; 

The output:

jpg

Wrapping Up

substr() gives you control over string parts based on position and length. It is simple, fast, and useful for many cases.

Here is a quick recap:

  • substr() returns part of a string with a start position and optional length.
  • Use positive or negative numbers to control where it starts and how much it returns.
  • If you leave out the length, PHP gives everything from the start to the end.
  • substr() works well to truncate text and slice values. Also to clean user input.
  • If the start index is too big, PHP returns an empty string.
  • If the length is too large, PHP stops at the end of the string.
  • Don’t use substr() inside loops unless needed.

Thank you for reading. Click here to see more PHP tutorials.

FAQ’s

How does substr() work in PHP?

It returns part of a string from a start position. You can also pass a length to control how many characters to return. Use negative values to start from the end of the string.

How to get a file extension using substr()?

Use strrpos() to find the last dot in the filename. Then use substr() to grab everything after that. Example: substr($file, strrpos($file, '.') + 1) gives the extension.

Similar Reads

PHP array_keys: How to Extract Keys in Arrays with Examples

This guide shows how PHP array_keys finds all keys in an array and how you can filter them by a…

PHP filter_id Function: How to Retrieve PHP Filter IDs

Before PHP 5.2, there was no built-in filter extension in PHP. You had to manually handle and sanitize input. PHP…

PHP Multidimensional Arrays: Data Manipulation

In web development, managing and manipulating data is one of the most common tasks. When it comes to storing complex…

MongoDB PHP Driver: Install and Get Started

Traditional relational databases like MySQL often take center stage. However, with the rise of NoSQL databases, MongoDB has emerged as…

How to Connect PHP to MongoDB

Connecting PHP to MongoDB allows you to integrate database functionalities into your web applications. MongoDB is a NoSQL database that…

PHP Type Juggling: How it Works Behind the Scenes

PHP type juggling refers to the dynamic system where the type of a variable is determined by its context in…

PHP str_repeat: How it Works with Examples

PHP gives you many string tools. One of them is php str_repeat. This function repeats a texts as many times…

PHP array_fill_keys: Create Arrays with Specific Keys

The PHP array_fill_keys function helps you to build an array where each key has the same value. What is the…

Get Last Insert ID in PHP with MySQL PDO and MySQLi

Keeping track of the last record inserted is often important. Whether you are managing user registrations, processing orders, or handling…

PHP array_diff_ukey Function: How it Works with Examples

The PHP array_diff_ukey function compares keys in two or more arrays. It returns the keys from the first array that…

Previous Article

PHP Bitwise Operators: AND, OR, XOR, NOT with Examples

Next Article

PHP mb_substr Function: How it Works with Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.