Skip to content
PHP Logo

How can the substr function be used with variables in PHP?

When using the substr function with variables in PHP, you need to pass the variable containing the string as the first argument, followed by the starting position and optionally the length of the substring you want to extract. This allows you to dynamically extract substrings from a variable's value.

php
$string = "Hello, World!";
$start = 7;
$length = 5;

$substring = substr($string, $start, $length);

echo $substring; // Outputs "World"