Jump to content

Partial text match in array?


doa24uk

Recommended Posts

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";

 

I've looked at several array search options (in_array,stristr) etc. none seem to work...

Link to comment
https://forums.phpfreaks.com/topic/195499-partial-text-match-in-array/
Share on other sites

You were almost there. You will need to run a foreach() on the array and check each value independantly. I'd use stristr for a case insensitive search

 

function searchArray($search, $array)
{
    foreach($array as $key => $value)
    {
        if (stristr($value, $search))
        {
            return $key;
        }
    }
    return false;
}

$searchValue = 'arau.org';
$position = searchArray($searchValue, $arrayVar);

if($position===false)
{
    echo "{$searchValue} was not found.";
}
else
{
    echo "{$searchValue} was found at position {$position}.";
}

Thanks!

 

I finally went with this ... just incase someone else is looking for the same thing...

 

 

$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;
    }
}  

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.