Monday 29 March 2021

Php: substr: Return part of a string

Signature

substr ( string $string , int $offset , int|null $length = null ) : string

 

Description

Returns the portion of string specified by the offset and length parameters.

 

If offset is non-negative, the returned string will start at the offset'th position in string, counting from zero.

If offset is negative, the returned string will start at the offset'th character from the end of string.

If string is less than offset characters long, false will be returned.

 

Example

$substr1 = substr($str1, 1, 2);

$substr2 = substr($str1, -3, 3);

 


substr_demo.php

#!/usr/bin/php

<?php

   $str1 = 'Hello';
   $substr1 = substr($str1, 1, 2);
   $substr2 = substr($str1, -3, 3);
   
    echo "\$str1: $str1\n";
    echo "\$substr1: $substr1\n";
    echo "\$substr2: $substr2\n";
?>

 

Output

$./substr_demo.php 

$str1: Hello
$substr1: el
$substr2: llo

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment