Hi guys,
My array is as follows:
Array
(
[0] => http://www.arau.org/ct_home.php
[1] => http://www.arau.org/
[2] => http://en.wikipedia.org/wiki/Arau
)
All I want to do is look for certain partial matches & output their position in the array. It shouldn't care about the other results ... just the first match
Eg. $string_to_match = "arau.org"
// If arau.org is found in array
echo "Found at position 0";
kbluhm
03-16-2010, 11:17 PM
Running out the door for a few, so I'll keep this quick... let me know if any explanation is needed. :)
function array_find( Array $array, $needle )
{
foreach ( $array as $key => $value )
{
if ( FALSE !== strpos( $value, $needle ) )
{
$index = $key;
break;
}
}
return isset( $index ) ? $index : FALSE;
}
Usage:
$links = array(
0 => 'http://www.arau.org/ct_home.php',
1 => 'http://www.arau.org',
2 => 'http://en.wikipedia.org/wiki/Arau',
);
if ( FALSE !== ( $index = array_find( $links, 'arau.org' ) ) )
{
echo 'Found at position ', $index; // Found at position 0
}
else
{
echo 'Not found';
}
timgolding
03-16-2010, 11:19 PM
$array = array( 'http://www.arau.org/ct_home.php','http://www.arau.org/','http://en.wikipedia.org/wiki/Arau');
foreach($array as $key => $value)
{
if(stristr($value, "arau.org"))
{
$partial_match_key = $key;
break;
}
}
Brilliant guys,
Both work perfectly (you've no idea how long I've messed about with this.
I'm using the second example as I can more easily see how it works.
Thanks again.
kbluhm
03-17-2010, 01:18 AM
PHP advises strpos() as faster and less memory intensive when compared to strstr().
Tim's method uses stristr(), which makes the match case-insensitive. Compliment that with stripos() for a faster case-insensitive search.