douduoting8408 2009-09-18 11:13
浏览 58
已采纳

在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

  • 写回答

5条回答 默认 最新

  • dongza1708 2009-09-18 11:20
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 基于作物生长模型下,有限水资源的最大化粮食产量的资源优化模型建立
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo
  • ¥15 科来模拟ARP欺骗困惑求解
  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式