Using String Position and Substring to Extract a Portion of a String using PHP

We’re going to use several string functions together. Let’s take the string testing testing Username:Michele Davis and retrieve only the name.

Using several functions together to extract a portion of a string

";
echo "$position
";
echo substr($test_string,$start);
?>

This Code Return

testing testing Username:Michele Davis
16
Michele Davis

Note: The number 16 in our example is the position of our username

Use strpos to search for Username: and return its position in the string with zero being the first position. Use strlen to add on to that position to find where you need to start extracting from the $test_string. To extract the name, use substr, which takes the string as a parameter, returning everything after the $position character in the string.

Share This Post

Post Comment