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

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

我有以下字符串 p>

  $ string =“18  DR 01 + 2 21.47 20.24 27.15 20.24 BE记录+ 2 24.05 22.68“
  code>   pre> 
 
 

我想在找到的第一个字母处将其拆分(每次字母都有所不同)。 我发现了一个类似的问题,其中包含以下示例 p>

  $ split = explode(' - ','orange-yellow-red',2); 
echo $ split [1  ]。  //输出黄色 - 红色
  code>  pre> 
 
 

但这假设您知道这封信是什么。 有没有办法指定任何字母? 我之前使用过preg split,但是不能限制,而且我对正则表达式也不是很好。 p>

如果爆炸可以使用正则表达式,那么这样的东西可能有用,但是这个 只是一个例子,因为这不起作用。 p>

  $ 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); 
  code>  pre> 
 

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.

Try preg_split.

preg_split('/[a-z]/i', $string, 2);

I see you want to keep the letter - if you want it to go with the string before, use a lookbehind:

preg_split('/(?<=[a-z])/i', $string, 2);

if you want it to go with the string after, use a lookahead:

preg_split('/(?=[a-z])/i', $string, 2);

If you want it separated, up the number of splits and use both.

preg_split('/(?<=[a-z])|(?=[a-z])/i', $string, 3);

Here you go: see it in action