0

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

$test_string="testing testing Username:Michele Davis";
$position=strpos($test_string,"Username:");

//add on the length of the Username:
$start=$position+strlen("Username:");

echo "$test_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.


Filed in: PHP Functions

Recent Posts

Bookmark and Promote!

© 2012 Sumit Bansal. All rights reserved. XHTML / CSS Valid.