dsfdsfsdf45489 2013-09-24 19:18
浏览 24
已采纳

php首次出现一个字母时拆分字符串

I have the following string

$string = "18/05-01/06 01/06-06/07 06/07-22/08 22/08-14/09 DR Record + 2 21.47 20.24 27.15 20.24 BE Record + 2 24.05 22.68"

I would like to split it at the first letter found (the letter varies each time). I found a similar question that had the following example

$split = explode('-', 'orange-yellow-red',2);
echo $split[1]; //output yellow-red

But this is assuming you know what the letter is. Is there a way to specify any letter? I've used preg split before but that can't limit and also i'm not that good with regex.

If explode would work with regex then something like this may work, but this is just an example as this would not work.

$string = "18/05-01/06 01/06-06/07 06/07-22/08 22/08-14/09 DR Record + 2 21.47 20.24 27.15 20.24";
$split = explode([A-Za-z], $string,2);
  • 写回答

2条回答 默认 最新

  • douke7431 2013-09-24 19:29
    关注

    Use preg_split

    $string = "18/05-01/06 01/06-06/07 06/07-22/08 22/08-14/09 DR Record + 2 21.47 20.24 27.15 20.24 BE Record + 2 24.05 22.68"
    
    $stringArray = preg_split("/[a-zA-Z]/",$string,2);
    

    the [a-zA-Z] tells it to find the first letter, and then it will split from there

    $stringArray will hold the two resulting strings, note that it takes out the letter that it split on

    You could though use preg_match to get the two strings so that it will not strip out the first letter

    preg_match("/([^a-zA-Z]+)(.*)/",$string,$Matches);
    

    here the regular expression tells it to capture everything up to the first letter, and then capture everything after that

    $Matches[1] would contain

    18/05-01/06 01/06-06/07 06/07-22/08 22/08-14/09 
    

    and $Matches[2] would contain

    DR Record + 2 21.47 20.24 27.15 20.24 BE Record + 2 24.05 22.68
    

    $Match[0] holds the whole string that was matched.

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

报告相同问题?

悬赏问题

  • ¥15 从Freecad中宏下载的DesignSPHysics,出现如下问题是什么原因导致的(语言-python)
  • ¥30 notepad++ 自定义代码补全提示
  • ¥15 MATLAB有限差分法解一维边值问题
  • ¥200 内网渗透测试 横向渗透 Windows漏洞 Windows权限维持
  • ¥15 数据结构图的相关代码实现
  • ¥15 python中aiohttp.client_exceptions.ContentTypeError
  • ¥30 DeepLung肺结节检测生成最大froc值对应的epoch报错
  • ¥15 信号发生器如何将频率调大,步尽值改成10
  • ¥15 keil 5 编程智能家具,风扇台灯开关,人体感应等
  • ¥100 找一名渗透方面的专家