Author Topic: Regular Expression help  (Read 389 times)

0 Members and 1 Guest are viewing this topic.

Offline BrettCarrTopic starter

  • Irregular
  • Posts: 17
    • View Profile
Regular Expression help
« on: March 14, 2010, 07:11:02 AM »
Quote
I want to put "],[" every thirteen commas with a regular expression
Quote
Im trying this is the string
Quote
$teststring = "2010-03-14,74527,645,New,7417417,Toll,2,74527417,32,202,7452741741,ghtgbwt,gtgwtgwtfgwtrg,2010-03-14,857527527,645,New,7417418,Toll,7,74527418,32,202,527527,hjm,djmdmdjmdjmdgjm,2010-03-14,85285,645,New,7417419,Toll,2,74527419,32,202,750757,jryjkryjkfryk,yjmyjyjtyjhm";
Quote
The first preg_replace puts commas around my strings
Quote
The next one is where im trying to put square brackets every 13 commas
<?php
$teststring 
"2010-03-14,74527,645,New,7417417,Toll,2,74527417,32,202,7452741741,ghtgbwt,gtgwtgwtfgwtrg,2010-03-14,857527527,645,New,7417418,Toll,7,74527418,32,202,527527,hjm,djmdmdjmdjmdgjm,2010-03-14,85285,645,New,7417419,Toll,2,74527419,32,202,750757,jryjkryjkfryk,yjmyjyjtyjhm";
$teststring1 =  preg_replace("/([a-zA-Z0-9_\-]+?),/" "\"$1\",",$teststring);
$teststring2 =  preg_replace("/\,{13}/" "],[",$teststring1);

var_dump($teststring2);
?>

Offline cags

  • Guru
  • Fanatic
  • *
  • Posts: 3,250
  • Gender: Male
    • View Profile
    • TiB Studios
Re: Regular Expression help
« Reply #1 on: March 15, 2010, 09:02:01 AM »
I'm not convinced using Regex is the best method to edit a CSV file (which is what you appear to be working with), but something like this perhaps...

$pattern '#(?:[^,]*,){12}[^,]*#';
$replacement '$0],[';


Disclaimer: That's completely untested.
CodeCanyon - Cheap, High Quality, Ready Made Scripts.

Offline sasa

  • Guru
  • Fanatic
  • *
  • Posts: 3,011
  • Gender: Male
    • View Profile
Re: Regular Expression help
« Reply #2 on: March 17, 2010, 02:39:33 PM »
try
Code: [Select]
<?php
$teststring 
"2010-03-14,74527,645,New,7417417,Toll,2,74527417,32,202,7452741741,ghtgbwt,gtgwtgwtfgwtrg,2010-03-14,857527527,645,New,7417418,Toll,7,74527418,32,202,527527,hjm,djmdmdjmdjmdgjm,2010-03-14,85285,645,New,7417419,Toll,2,74527419,32,202,750757,jryjkryjkfryk,yjmyjyjtyjhm";
//$teststring1 =  preg_replace("/([a-zA-Z0-9_\-]+?),/" , "\"$1\",",$teststring);
//$teststring2 =  preg_replace("/\,{13}/" , "],[",$teststring1);
$a array_chunk(explode(',',$teststring),13);
foreach (
$a as $k => $b$a[$k] = '"'.implode('","'$b).'"';
$teststring2 implode('],[',$a);
var_dump($teststring2);
?>