PHP substr() function

5 (100%) 1 vote
<?php
 
// PHP program to illustrate substr()
function Substring($str){
    $len = strlen($str);
    echo substr($str, 8), "\n";
    echo substr($str, 5, $len), "\n";
    echo substr($str, -5, 10), "\n";
    echo substr($str,-8, -5), "\n";
}
 
// Driver Code
$str="blogsforblogs";
Substring($str);
 
?>

Output:

blogs
forblogs
blogs
for



The substr() is a built-in function in PHP that is used to extract a part of string.

Syntax:

substr(string_name, start_position, string_length_to_cut)

Parameters:
The substr() function allows 3 parameters or arguments out of which two are mandatory and one is optional.

yntax

substr(string,start,length)

 

Parameter Description
string Required. Specifies the string to return a part of
start Required. Specifies where to start in the string

  • A positive number – Start at a specified position in the string
  • A negative number – Start at a specified position from the end of the string
  • 0 – Start at the first character in string
length Optional. Specifies the length of the returned string. Default is to the end of the string.

  • A positive number – The length to be returned from the start parameter
  • Negative number – The length to be returned from the end of the string
<!DOCTYPE html>
<html>
<body>

<?php
echo substr("Hello world",6);
?>

</body>
</html>

Output:

world

Another Example:

<!DOCTYPE html>
<html>
<body>

<?php
// Positive numbers:
echo substr("Hello world",10)."<br>";
echo substr("Hello world",1)."<br>";
echo substr("Hello world",3)."<br>";
echo substr("Hello world",7)."<br>";
echo "<br>";

// Negative numbers:
echo substr("Hello world",-1)."<br>";
echo substr("Hello world",-10)."<br>";
echo substr("Hello world",-8)."<br>";
echo substr("Hello world",-4)."<br>";
?>

</body>
</html>

Output:

d
ello world
lo world
orld

d
ello world
lo world
orld

For any query or issue, feel free to discuss on http://discuss.eduguru.in
%d bloggers like this: