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

3 php

我知道我们有 php in_array 函数

但我正在寻找一种方法来查找以特定字符串开头的字符串数组中的值

例如找到...

$search_string = '<div>1</div>';
Run Code Online (Sandbox Code Playgroud)

在这样的数组中...

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

那有意义吗

Pas*_*TIN 6

您可以在数组的所有行上循环,并strpos在每个字符串上使用 ; 有点像这样:

$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);
  }
}
Run Code Online (Sandbox Code Playgroud)

这将为您提供以搜索字符串开头的行的键:

string 'sample' (length=6)
Run Code Online (Sandbox Code Playgroud)


或者preg_grep也可以解决这个问题:

返回由输入数组中与给定模式匹配的元素组成的数组。

例如 :

$result = preg_grep('/^' . preg_quote($search_string, '/') . '/', $array);
var_dump($result);
Run Code Online (Sandbox Code Playgroud)

(别忘了使用preg_quote!)

会给你:

array
  'sample' => string '<div>1</div><p>fish food</p>' (length=28)
Run Code Online (Sandbox Code Playgroud)

请注意,这样,您不会获得密钥,而只能获得该行的内容。