Function to Extract The Value From a String With PHP

By | August 8, 2008

If you’re working with text information, you often need to extract some parts of text from articles, web pages and so on. You can use regular expressions for this, but if you’re not familiar with them, you’ve got to use string functions of PHP.

When I didn’t know what regular expressions are, I’ve written a function that extracts the text you need from a string. It is useful when you need to parse forms, web pages for some exact information, etc. Here it is:

<?

function extract_value($source, $start, $end)
{
$pos=@strpos($source, $start)+strlen(stripslashes($start));
$pos2=@strpos($source, $end, $pos);
$len=$pos2-$pos;
$output=substr($source, $pos, $len);
return $output;
}

?>

Function above takes three arguments: text source, the first matching part and the second matching part. Function extracts the text between these two values. Sample usage is: $match=extract_value($result, “from here”, to here”); This is much easier than to deal with regular expressions, especially if you are new to PHP. This function is not for professionals, however it is a great solution if you often need to parse something from text without regular expressions.