PHP substr() string function



The substr() function in PHP

The substr() function used to returns some portion of given string by assign start and length values.

substr() function syntax

substr(“string”, start, length);

PHP strsub() function example

<?php
echo "The substring of stirng = ". substr("Meera Academy",1,6);
?>

In above strsub() function example the string = “Meera Academy” and start from 1st index to 6 character .The index value always start from 0, so here we assign start to 1 then the string returns from second character to six character.

The white space calulated in a string.

The out put is :

The substring of stirng = eera A

substr() function example with php form

Here, we create php form firstexample.php with three textboxes and a submit button control. In first textbox get string value from user and second textbox is the start position of substring and the last length textbox is the character length of substring.

<html>
<head>
<title>PHP strlen() Function</title>
</head>
<body>

<FORM method="POST" action="firstexample.php">

Name : <input type="text" name="name"> <br/><br/>
Start : <input type="text" name="start"> <br/>
Length : <input type="text" name="len"></br></br>
<input type="submit" name="Submit1" value="String Length">

</FORM>

<?php
if(isset($_POST['Submit1']))
{
echo "The substring of stirng = ". substr($_POST["name"],$_POST["start"],$_POST["len"]);
}
?>

</body>
</html>

In above php substr() function we entered “Meera Academy” text in name textbox and the start postion =1 and the length=6, so out put result = “eera A”. The first character start position is 0.

PHP substr() string function
PHP substr() string function

 

2 thoughts on “PHP substr() string function

  1. If we only use 2 parameters for substr function (string and start)
    for example

    echo substr(“hello”, 1);

    The output will show “ello”

    So length parameter can be optional

    1. Yes, length parameter is optional, but we do not use length then the full string will be return from starting poiint.

      substr(“meeraacademy”,1,5);
      result = eeraa

      substr(“meeraacademy,1);
      result = eeraacademy

Leave a Reply to Meera Academy Cancel reply

Your email address will not be published. Required fields are marked *