Extract a Substring from a String with the substr() Function in PHP
Learn how to use the substr() function in PHP to extract a substring from a string. See examples and sample code to help you use this function in your PHP projects. Whether you need to get a specific portion of a string or just want to extract a certain number of characters, substr() is the perfect tool to get the job done.
In PHP, the substr()
function is used to extract a portion of a string. The function takes three parameters: the string, the starting position, and the length of the substring to be extracted.
For example, consider the following string:
<?php
$string = "Hello, World!";
?>
To extract the word “Hello” from the string, you would use the following code:
<?php
$substring = substr($string, 0, 5);
echo $substring; // Outputs "Hello"
?>
You can also use negative values for the starting position, in which case the function will start counting from the end of the string. For example, to extract the last three characters of a string:
<?php
$string = "Hello, World!";
$substring = substr($string, -3);
echo $substring; // Outputs "ld!"
?>
You can also use the substr_replace()
function to replace a portion of a string with a new string. This function takes four parameters: the original string, the replacement string, the starting position and the length of the portion to be replaced.
<?php
$string = "Hello, World!";
$new_string = substr_replace($string, "Universe", 7, 6);
echo $new_string; // Outputs "Hello, Universe!"
?>
In this example, the string “World” starting from the 7th position is replaced with the string “Universe” with 6 length.