Find start of string inside array of strings in php

I know we have php function in_array

but I'm looking for a way to find values ​​in a string array that starts matching 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>
);

      

it makes sense

+2


source to share


5 answers


You can either loop through all the lines of the array, or use strpos

for each line; like that:

$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 give you the key of the string starting with your search string:

string 'sample' (length=6)

      


Or preg_grep can do the trick as well:

Returns an array of input array elements that match the specified pattern.



For example:

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

      

(Don't forget to use preg_quote

!)

You'll get:

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

      

Note that you don't get the key this way, only the contents of the string.

+2


source


+4


source


For this you need to use regular expressions. Check out the tutorial .

+1


source


Why don't you just iterate over the array and check the regex 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;
  }
}

      

+1


source


If you only need to figure out if any line starts in $array

with $search_string

(basically the in_array () alternative will check for the beginning of the line), you can also use array_reduce () :

array_reduce($array, function ($contains, $item) use ($search_string) {
    return $contains = $contains || (strpos($search_string, $item) === 0);
}, false);

      

+1


source







All Articles