Mon 17 Nov 2008
so, the question goes a-like-a this: write a function that, given an array of strings, will return the number of those strings that contain the letters c,h,e,v,r,o and n in that order. there may or may not be other letters around and in between. Here’s was my first attempt:
$strings = array( "i like cheetos, but everyone knows cheez-its are better", "che guevara was born in argentina", "i own a chevrolet", "hello world" ); echo(chevronMatch($strings)); function chevronMatch($strings) { $chevron="chevron"; $chevronCount=0; foreach($strings as $testString) { $hitCount=0; for($y=0;$y<strlen($testString);$y++) { if ($testString[$y]==$chevron[$hitCount]) { if ($hitCount<strlen($chevron)-1) { $hitCount++; } else { $chevronCount++; break; } } } } return $chevronCount; }
Obviously, iterative code like that would make a regex guru like bj upset. here’s my second attempt, this time with ereg
function chevronMatch($strings) { $chevronsMatched=0; foreach($strings as $string) { $chevron=array('c','h','e','v','r','o','n'); $regex="[a-z,\-\ ]*"; $regexString=$regex.implode($regex,$chevron).$regex; if (ereg($regexString,$string)) $chevronsMatched++; } return $chevronsMatched; }
HA! I was totally going to post a regex solution! Your second solution is much nicer IMO, though the use of the ereg* functions in PHP is generally considered deprecated. Instead use preg_match. Also, you’re searching case-sensitively, which you shouldn’t be. In the end, this is a bit cleaner version (though the guts are solid and remain mostly unchanged):
function chevronMatch($strings)
{
$chevronsMatched=0;
foreach($strings as $string)
{
$chevron=array(‘c’,‘h’,‘e’,‘v’,‘r’,‘o’,‘n’);
$regex=”[a-z,- ]*”;
$regexString=’/’.$regex.implode($regex,$chevron).$regex.’/i’;
if (preg_match($regexString,$string)) $chevronsMatched++;
}
return $chevronsMatched;
}
On another note, preg_replace allows you to pass it an array of subject data and an array of replacement data. Seems like they could allow the same for preg_match.