ADVERTISEMENTS

How to get substring from a string in PHP

PHP provides a variety of built-in functions for working with strings. We can get substring with help of the substr() function which is used to extract a portion of a string. The function takes three parameters: the string, the start position, and the length of the substring.

The following example will explain the process of getting substring from a string on the basis of parameters :

<?php
$main_string = "Etutorialz is best learning portal";
$substring = substr($main_string, 0, 10);
?>

In this example, the variable $substring would contain the string "Etutorialz".

Note that the start position is zero-based, so the first character of the string is position 0. If you want to get the last n characters of a string you can use negative values on the start parameter, for example:

 

<?php
$string = "Etutorialz is best learning portal";
$substring = substr($string, -6); // Output: "portal"
?>

PHP (Hypertext Preprocessor) is a server-side scripting language used to create web pages and web applications. It can be embedded into HTML and is often used in combination with databases such as MySQL to create dynamic, interactive websites. You can learn php from our PHP Tutorials and PHP Examples

ADVERTISEMENTS