Alternatives to Regular Expressions
As a php programmer who has to deal daily with regular expressions, sometimes they are just overkill for a simple job. Other times, I just don’t feel like trying to figure out the regex when I am trying to extract content just once (and code optimization is just not important). Below,I have thrown together a handful of PHP functions that I regularly use to help accomplish these tasks.
GetSingleMatch
This code allows you to easily grab a single bit of text out of a document by describing what text or code occurs right before and right after the text you are targetting. This calls for the $start, $end, and $content. If I were trying to target the word “fox” in “the quick brown fox jumps”, i would use, getSingleMatch(“brown “,” jumps”,”the quick brown fox jumps”)
function getSingleMatch($start,$end,$content) {
$exp = explode($start,$content);
$exp2 = explode($end,$exp[1]);
return $exp2[0];
}
getMultiMatch
The getMultiMatch function is similar, but it returns many matches in an array. This is very useful in finding all of the hrefs in a document, for example, by doing getMultiMatch(‘href=’,’ ‘,$content);
function getMultiMatch($start,$end,$content) {
$exp = explode($start,$content);
for($i=1;$i< count ( $exp );$i++) {
$exp2 = explode($end,$exp[$i]);
$arr[] = $exp2[0];
}
return $arr;
}
Recent Comments