PHP - String String substring

Introduction

To extract a sequence of characters from a string, use PHP's substr() function.

This function takes the following parameters:

  • string to extract the characters from
  • position to start extracting the characters. If you use a negative number, substr() counts backward from the end of the string
  • number of characters to extract. If you use a negative number, substr() misses that many characters from the end of the string instead.

The third parameter is optional; if left out, substr() extracts from the start position to the end of the string

Demo

<?php
$myString = "Hello, world!";
echo substr( $myString, 0, 5 ) . " \n ";  
echo substr( $myString, 7 ) . " \n ";    
echo substr( $myString, -1 ) . " \n ";    
echo substr( $myString, -5, -1 ) . " \n "; 
?>//  w  w  w. j  a v a 2  s . c  om

Result

Related Topic