Learn How To Use Substr Function With Example In PHP

admin_img Posted By Bajarangi soft , Posted On 24-09-2020

The substr() function used to extract a part of string.

PHP substr Function with example

Syntax of substr() function and Usage

substr(string,start,length)


Parameter Values

string   -> The input string

start    -> This specifies from where to start in the input string.
            1.positive number ->returned string will start at the specified position.
            2.negative number ->returned string will start at the specified position from the end.
            3.zero->start at the first character in string.

length   ->this is optional. specifies the length of the returned string.
            1.positive number ->The length to be returned from the start parameter(depending on the length of string)
            2.negative number ->The length to be returned from the end of the string(after the start position has been
                                 calculated when a start is negative)
            3.If length is given and is 0, FALSE or NULL, an empty string will be returned.


Let's learn

1.Create string.

$string="BAJARANGISOFT";


2.Print string using substr() function.

echo substr($string, 6);


Example(1)

<?php
$string="BAJARANGISOFT";
echo substr($string, 4);
?>


Example(2)

<?php
echo substr("BAJARANGISOFT",8)."<br>";
echo substr("BAJARANGISOFT",3)."<br>";
echo substr("BAJARANGISOFT",11)."<br>";
echo substr("BAJARANGISOFT",5)."<br>";

echo substr("BAJARANGISOFT",-3)."<br>";
echo substr("BAJARANGISOFT",-8)."<br>";
echo substr("BAJARANGISOFT",-6)."<br>";
echo substr("BAJARANGISOFT",-2)."<br>";
?>


Complete Code of substr() Function:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>PHP substring function</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="text-center">
        <h1>PHP substr() Function</h1>
    </div>
    <br>
    <h2>The substr() function used to extract a part of string</h2>
    <div class="well">
        <?php
        $string="BAJARANGISOFT";
        echo "<h1>".substr("BAJARANGISOFT",0). "</h1>";
        echo "<h4>".substr($string, 4) ."</h4>" ;
        echo "<h4>".substr("BAJARANGISOFT",8). "</h4>";
        echo "<h4>".substr("BAJARANGISOFT",3). "</h4>";
        echo "<h4>".substr("BAJARANGISOFT",11)."</h4>";
        echo "<h4>".substr("BAJARANGISOFT",5). "</h4>";
        echo "<h4>".substr("BAJARANGISOFT",-3)."</h4>";
        echo "<h4>".substr("BAJARANGISOFT",-8)."</h4>";
        echo "<h4>".substr("BAJARANGISOFT",-6)."</h4>";
        echo "<h4>".substr("BAJARANGISOFT",-2)."</h4>";
        ?>
    </div>
    <br>
</div>
</body>
</html>

Related Post