3

I know we have the php in_array function

but I'm looking for a way to find values in an array of strings who beginning matches a specific string

for example find...

$search_string = '<div>1</div>';

in an array like this...

$array = (
    'sample'  => '<div>1</div><p>fish food</p>',
    'sample2' => '<div>2</div><p>swine</p>
);

does that make sense

4 Answers4

6

You can either loop on all lines of the array, and use strpos on each string ; a bit like this :

$search_string = '<div>1</div>';
$array = array(
    'sample'  => '<div>1</div><p>fish food</p>',
    'sample2' => '<div>2</div><p>swine</p>'
);

foreach ($array as $key => $string) {
  if (strpos($string, $search_string) === 0) {
    var_dump($key);
  }
}

Which will get you the key of the line that starts with your search string :

string 'sample' (length=6)


Or preg_grep might do the trick too :

Returns the array consisting of the elements of the input array that match the given pattern .

For instance :

$result = preg_grep('/^' . preg_quote($search_string, '/') . '/', $array);
var_dump($result);

(Don't forget to use preg_quote ! )

Will get you :

array
  'sample' => string '<div>1</div><p>fish food</p>' (length=28)

Note that, this way, you don't get the key, but only the content of the line.

Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
  • I decided to go with strpos because I thought it woul be more efficient than a regular expression and I have a lot of control over the string –  Sep 22 '09 at 15:02
3

Try preg_grep() or array_filter().

Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
1

If you only need to find whether any string within the $array begins with the $search_string (basically an alternative in_array() that would check beginning of the string), you could also use array_reduce():

array_reduce($array, function ($contains, $item) use ($search_string) {
    return $contains = $contains || (strpos($search_string, $item) === 0);
}, false);
Janci
  • 3,198
  • 1
  • 21
  • 22
0

Why don't you just cycle over your array and check with a regular expression, or strstr, or substr(...) == $search_string?

$res = "";
foreach($array as $key => $value) {
  if(substr(0, strlen($search_string)-1, $value) == $search_string) {
    $res = $key;
    break;
  }
}
Palantir
  • 23,820
  • 10
  • 76
  • 86