substr in php

If you know where the data that you are interested in lies in a larger string, you can copy it out with the substr() function:

$piece = substr(string, start [, length ]);

The start argument is the position in string at which to begin copying, with 0 meaning the start of the string. The length argument is the number of characters to copy (the default is to copy until the end of the string). For example:

$name = “Fred Flintstone”;
$fluff = substr($name, 6, 4); // $fluff is “lint”
$sound = substr($name, 11); // $sound is “tone”

More eample of substr in php

<?php
$rest = substr("abcdef", -1);    // returns "f"
$rest = substr("abcdef", -2);    // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
?>
<?php
$rest = substr("abcdef", 0, -1);  // returns "abcde"
$rest = substr("abcdef", 2, -1);  // returns "cde"
$rest = substr("abcdef", 4, -4);  // returns ""; prior to PHP 8.0.0, false was returned
$rest = substr("abcdef", -3, -1); // returns "de"
?>
<?php
echo substr('abcdef', 1);     // bcdef
echo substr('abcdef', 1, 3);  // bcd
echo substr('abcdef', 0, 4);  // abcd
echo substr('abcdef', 0, 8);  // abcdef
echo substr('abcdef', -1, 1); // f

// Accessing single characters in a string
// can also be achieved using "square brackets"
$string = 'abcdef';
echo $string[0];                 // a
echo $string[3];                 // d
echo $string[strlen($string)-1]; // f

?>

Leave a Comment