PHP Developer Question:
How you take a substring from a given string in PHP?
Answer:
If you know the position of a substring in a given string, you can take the substring out by the substr() function. Here is a PHP script on how to use substr():
<?php
$string = "beginning";
print("Position counted from left: ".substr($string,0,5)." ");
print("Position counted form right: ".substr($string,-7,3)." ");
?>
This script will print:
Position counted from left: begin
Position counted form right: gin
substr() can take negative starting position counted from the end of the string.
<?php
$string = "beginning";
print("Position counted from left: ".substr($string,0,5)." ");
print("Position counted form right: ".substr($string,-7,3)." ");
?>
This script will print:
Position counted from left: begin
Position counted form right: gin
substr() can take negative starting position counted from the end of the string.
Previous Question | Next Question |
Which is the best way to test the strpos() Return Value in PHP? | How to replace substring in a given string in PHP? |