Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using regex and php

Tags:

regex

php

I have been trying to figure out how to convert string below string to multiple lines where it will add comma after two consecutive letters. Anyhelp is appreciated.

$myLine = "1234:21:3AB3459435:2343RT23432523:CD";
$myLine= preg_replace('/((?<=\[a-zA-Z]\b))/', ',', $myLine);

output would be

1234:21:3AB,
3459435:2343RT,
23432523:CD,

THanks, jp

I like all the answers, i appreciate everyone pitching in to help and ran through all the various different ways of getting this to work. it is amazing what regexp php can do one thing so many different ways. thanks to all again!!!!

like image 791
jpp Avatar asked Feb 22 '26 08:02

jpp


2 Answers

Here's something I came up with quickly.

$myLine = "1234:21:3AB3459435:2343RT23432523:CD";
$myLine= preg_replace('/([a-zA-Z]{2})/', "$1,\n", $myLine);

Outputs:

1234:21:3AB,
3459435:2343RT,
23432523:CD,

Or, if you don't want the trailing comma:

$myLine = "1234:21:3AB3459435:2343RT23432523:CD";
$myLine= preg_replace('/([a-zA-Z]{2}(?!$))/', "$1,\n", $myLine);

Outputs:

1234:21:3AB,
3459435:2343RT,
23432523:CD
like image 74
Rocket Hazmat Avatar answered Feb 24 '26 22:02

Rocket Hazmat


$myLine = "1234:21:3AB3459435:2343RT23432523:CD";
$myLine = preg_replace('/([a-z]{2})/i', '$1,', $myLine);
like image 29
Erveron Avatar answered Feb 24 '26 20:02

Erveron