Menu

Add Topic

programming

waiting answer July 28, 2021

How to extract substring from a string in PHP

Answers
June 10, 2021

substr() is a built-in function in PHP and it returns the extracted part of the string.

Syntax

          substr(string_name, position, length);

  • string_name => name of the string, required parameter
  • position => start position, required parameter
  • length => string length to cut , optional parameter

Example

     <?php
        $rest = substr("restaurant", -1);    // returns "t"
        $rest = substr("restaurant", -2);    // returns "nt"
        $rest = substr("restaurant", -3, 1); // returns "a"
    ?>
0 0
June 10, 2021

The PHP function substr() can be used to extract substrings from a string. 

Let's check out the example of how basically this works.

     <?php
        echo substr("Welcome to America",11)."<br>"; // Outputs: America
        echo substr("Welcome to America",1)."<br>"; // Outputs: elcome to America
        echo substr("Welcome to America",3)."<br>"; // Outputs: come to America
        echo substr("Welcome to America",7)."<br>"; // Outputs: to America
        echo substr("Welcome to America",-1)."<br>"; // Outputs: a
        echo substr("Welcome to America",-10)."<br>"; // Outputs: to America
        echo substr("Welcome to America",-8)."<br>"; // Outputs: America
        echo substr("Welcome to America",-4)."<br>"; // Outputs: rica
    ?>
0 0

Please Login to Post the answer

Leave an Answer