PHP substr Tutorial: Everything You Need to Know

The PHP substr function is a fundamental string tool for PHP developers. In this article we explain PHP substr basics, show substr in PHP examples, and compare PHP substr with multibyte-safe alternatives so you can choose the right approach for production code.

PHP substr example

Table of Contents

Basics of PHP substr

The PHP substr function extracts a portion of a string and is commonly used for quick slicing, prefix removal, and truncation. The most common signature you will see is:

PHP
substr(string $string, int $start, ?int $length = null): string
  • $string — the input string.
  • $start — the 0-based starting offset.
  • $length — optional trimmed length; if omitted, the slice runs to the end.

PHP substr Syntax and Parameters

When using PHP substr keep these rules in mind:

  • Offsets are zero-based.
  • Negative $start or negative $length count from the end of the input string.
  • If $length is omitted, the function returns everything from $start to the end.
  • When input is empty, the function returns an empty string.

PHP substr Code Examples

Simple extraction:

PHP
<?php
$s = "Hello, Programmer Notes!";
echo substr($s, 7, 7); // outputs "Program"
?>

Last N characters:

PHP
<?php
$s = "example.txt";
echo substr($s, -4); // outputs ".txt"
?>

Empty and out-of-range values:

PHP
<?php
$s = "";
var_dump(substr($s, 0, 5)); // string(0) ""
var_dump(substr("abc", 10, 2)); // string(0) ""
?>

Negative Offsets and Lengths

PHP substr supports negative values for $start and $length. For example substr($s, -3) returns the last three characters, while substr($s, 0, -1) returns all but the last character.


Multibyte Strings and PHP substr

Because PHP substr operates on bytes, it is not safe for multibyte encodings such as UTF-8. For user-facing text you should use mb_substr from the mbstring extension:

PHP
<?php
$s = "Olá mundo";
echo mb_substr($s, 0, 3, 'UTF-8'); // outputs "Olá"
?>

If you must use byte-based slicing (for binary protocols or byte offsets), PHP substr is appropriate; for textual data use multibyte-aware alternatives.


substr in PHP — Real World Examples

Common real-world uses for substr in PHP include:

  • Trimming known prefixes or suffixes from filenames.
  • Parsing fixed-width legacy data.
  • Creating short previews (but prefer multibyte-safe methods for user text).
  • Simple token extraction when the format is fixed.

Example — fixed-width parsing:

PHP
<?php
$line = "20251031John Smith      0001234";
$year = substr($line, 0, 4);
$name = trim(substr($line, 4, 16));
$amount = (int)substr($line, 20, 7);
?>

Laravel Substring

When working inside Laravel you can use helpers that are more expressive and often multibyte-aware. Laravel’s Str helper includes methods that mirror basic substring functionality:

PHP
use Illuminate\Support\Str;

echo Str::substr('Übercool', 0, 3); // returns 'Übe' if mbstring support is present
echo Str::limit('This is a long string', 10); // 'This is...'

Prefer Str::substr or Str::limit in application code for readability and framework consistency — these helpers often handle encoding edge cases better than raw slicing.


Smarty substr

In Smarty templates you can apply a modifier to crop values in the presentation layer:

PHP
{$value|substr:0:50} {* returns the first 50 characters of $value *}

Use Smarty substr when truncation is purely presentational. Avoid heavy logic in templates; perform business logic in PHP and leave templates to formatting.


Common Pitfalls

  • UTF-8 issues: using byte-based slicing on multibyte text can break characters.
  • Off-by-one errors: remember the zero-based indexing.
  • HTML entities: truncation can break &amp; or other entities if slices split them; decode or handle entities first.
  • Performance: repeated slicing in tight loops may be inefficient; cache values where appropriate.

Best Practices with PHP substr

  • Prefer mb_substr for user-facing, multi-language text.
  • Validate inputs (start/length) before slicing to avoid surprises.
  • Use framework helpers (such as Laravel substring helpers) for clearer semantics.
  • Keep presentation truncation in templates (Smarty substr) and processing truncation in backend code.

Testing and Edge Cases

Test behavior on:

  • Empty strings
  • Extremely large offsets
  • Multibyte characters and combining marks
  • HTML-encoded input

Unit tests should include edge-case assertions to prevent regression.


PHP substr FAQ

Is php substr zero-based?

Yes — offsets start at zero.

How do I get the last N characters?

Use a negative start: substr($s, -$n).

When should I use smarty substr vs backend slicing?

Use smarty substr for presentation-level truncation; use backend functions when manipulating or storing data.

Does substr in php return false ever?

In modern PHP it returns an empty string for out-of-range slices; behavior can vary across versions — check your PHP version docs and test.


Final notes

The PHP substr function is a quick, efficient tool for simple slicing tasks. For robust, production-ready handling of user text, pair it with multibyte-aware functions or framework helpers (Laravel substring) and use template modifiers (Smarty substr) only for display-layer truncation. Validate inputs and add tests for edge cases to avoid subtle bugs.

See the PHP Programming category for more PHP programming tips.

Reference: The official PHP substr documentation.