如何在字符串之间用“,”分隔两个数组,然后是

编程入门 行业动态 更新时间:2024-10-12 05:47:50
如何在字符串之间用“,”分隔两个数组,然后是 - ?(How to form two arrays from string separated by “,” and followed by -?) $str="a,b,c,d-e,f,g,h"

我试图从$str中提取字符串,这些字符串$str “,”分隔,并且在一个数组中以“ - ”分隔,字符串以“,”分隔,并在第二个数组中以“ - ”分隔。 这样$arr1=array(a,b,c,d); 和$arr2=array(e,f,g,h); 。 我只是使用$str作为例子,通常我希望这适用于任何相同形式的字符串,即$str=s1,s2,s3,s4,s5,....-r1,r2,t3....

注意:如果$str没有“ - ”,那么$arr2消失,并且$arr1包含$str由','分隔的元素数组。

这是我试过的

preg_match_all('~(^|.*,)(.*)(,.*|\-|$)~', $str, $arr1); preg_match_all('~(-|.*,)(.*)(,.*|$)~', $str, $arr2);

但是每个数组都带有一个包含字符串str元素。 有谁知道为什么这不起作用。

$str="a,b,c,d-e,f,g,h"

I am trying to extract the strings from $str that are separated "," and are before "-" in one array and the strings separated by "," and are after "-" in second array. So that $arr1=array(a,b,c,d); and $arr2=array(e,f,g,h);. I am just using $str as an example and generally I want this to work for any string of the same form i.e. $str=s1,s2,s3,s4,s5,....-r1,r2,t3....

NOTE: If $str doesn't have "-" then $arr2 vanishes and $arr1 contains an array of the elements separated by ',' in $str.

This is what I tried

preg_match_all('~(^|.*,)(.*)(,.*|\-|$)~', $str, $arr1); preg_match_all('~(-|.*,)(.*)(,.*|$)~', $str, $arr2);

However each array comes with one element that contains the string str. Does anyone know why this is not working.

最满意答案

^(.*?(?=-|$))|(?<=-)(.*$)

你可以使用它来获得2数组。参见演示。

https://regex101.com/r/vV1wW6/19

您的正则表达式不起作用,因为您使用了greedy修饰符。 .*,将在最后一次停止,

编辑:

使用这是你想要的字符串后-在第二组。

^(.*?(?=-|$))(?:-(.*$))?

https://regex101.com/r/vV1wW6/20

^(.*?(?=-|$))|(?<=-)(.*$)

You can use this to get 2 arrays.See demo.

https://regex101.com/r/vV1wW6/19

Your regex is not working as you have used greedy modifier..*, will stop at the last instance of ,

EDIT:

Use this is you want string after - to be in second group.

^(.*?(?=-|$))(?:-(.*$))?

https://regex101.com/r/vV1wW6/20

更多推荐

本文发布于:2023-08-04 20:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1422696.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字符串   两个   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!