3

I have a problem with preg_split. I need a regex to split my string into number and character. An example of my string is:

1_AB_CD_2_ABC_3_ABD

and I want a result splitted:

1
AB_CD
2
ABC
3
ABD

I've tried with this regex expression but this one not work:

 preg_split("/(^\d)(?=_)|(?<=_)(\d)(?=_)/",$sequence,PREG_SPLIT_DELIM_CAPTURE).
HamZa
  • 14,671
  • 11
  • 54
  • 75

1 Answers1

1
(?<=\d)_(?=[A-Z0-9]{2})|(?<=[A-Z0-9]{2})_(?=\d)

Try this.See demo.

https://regex101.com/r/uE3cC4/26

$returnValue = preg_split('/(?<=\\d)_(?=[A-Z0-9]{2})|(?<=[A-Z0-9]{2})_(?=\\d)/', '1_AB_CD_2_ABC_3_ABD', -1, PREG_SPLIT_NO_EMPTY);
vks
  • 67,027
  • 10
  • 91
  • 124
  • I've tried your solution but not work. :( Splitted string are incorrect – Vincenzo Di Roberto May 04 '15 at 07:51
  • I've tried your solution: ($result=preg_split("/(?<=\d)_(?=[A-Z])|(?<=[A-Z])_(?=\d)/",$sequence)) but not work. :( Splitted string are incorrect : 1_ITBI1303000100_2_ITTO10051004_3_ITTO10060018_4_ITBI1303000100 return with this expression "1 ITBI1303000100_2 ITTO10051004_3 ITTO10060018_4 ITBI1303000100 ".... – Vincenzo Di Roberto May 04 '15 at 07:57
  • Sorry but with preg_split still doesn't work. I've tried with or without PREG_DELIM_CAPTURE $result=preg_split("/(?<=\\d)_(?=[A-Z])|(?<=[A-Z])_(?=\\d)/",$sequence,PREG_SPLIT_DELIM_CAPTURE) $result=preg_split("/(?<=\\d)_(?=[A-Z])|(?<=[A-Z])_(?=\\d)/",$sequence) – Vincenzo Di Roberto May 04 '15 at 08:10
  • @VincenzoDiRoberto it is working for me.I have included the working code as well in the naswer.dont know what's d issue at ur end :( – vks May 04 '15 at 08:12
  • i have already tried your demo with real string and your demo doesn't work :( You can test it with this string:1_ITBI1303000100_2_ITTO10051004_3_ITTO10060018_4_ITBI1303000100 – Vincenzo Di Roberto May 04 '15 at 12:46
  • it works well in every case but not in this one: "1_HUB _SIT_RIVALTA_2_HUB_3SAAA_3_IT8739292" because there is a possibility that a segment has number and string and can start with number.... i know it is very difficult :( – Vincenzo Di Roberto May 04 '15 at 13:25