Jump to content

Recommended Posts

I want to put "],[" every thirteen commas with a regular expression

Im trying this is the string

$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";

The first preg_replace puts commas around my strings

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);
?>

Link to comment
https://forums.phpfreaks.com/topic/195182-regular-expression-help/
Share on other sites

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.

try

<?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);
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.