在php中查找字符串数组中的字符串的开头

问题描述:

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

我知道我们有php in_array函数 p>

但我正在寻找 找到一个开始匹配特定字符串的字符串数组中的值的方法 p>

例如find ... p>

  $ search_string  ='&lt; div&gt; 1&lt; / div&gt;'; 
  code>  pre> 
 
 

在这样的数组中...... p>

  $ array =(
'sample'=&gt;'&lt; div&gt; 1&lt; / div&gt;&lt; p&gt; fish food&lt; / p&gt;',
'sample2'=&gt;'&lt; div&gt; 2&lt;  ; / div&gt;&lt; p&gt; swine&lt; / p&gt; 
); 
  code>  pre> 
 
 

这是否有意义 p> div>

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.

You need to use regular expressions for that. Check this tutorial.

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

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