我试图从$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
更多推荐
发布评论