Jump to content

[SOLVED] unexpected results from preg_replace_callback


michaellunsford

Recommended Posts

The purpose of this code is to turn an abritrarily delimited file into a CSV. The RegEx appears to be valid (I tested it in a RegEx testing widget I have) but the following code returns the every single line, including non-matching lines. It also does not return the specific matches. I've also determined that regardless of what goes inside create_function, the results are always the same: every single line I pass the preg_replace_callback -- even ones that don't match.

 

Any ideas what I'm doing wrong?

 

<?php
ini_set("auto_detect_line_endings","1");
$regex="/^([^0-9]+)([0-9\/]+) (\$[0-9,\.]+) ([a-z ]+)$/i";
$i=0;
if ($handle = opendir('txt')) {
    while (false !== ($file = readdir($handle))) {
        if(preg_match("/\.txt/i",$file)) $get_file[$i++]="txt/".$file;
    }
    closedir($handle);
}
do {
$replace=array("\r","\n");
$with=array("","");
$fil=fopen(current($get_file),"r");
while(!feof($fil)) {
	$myrow=str_replace($replace,$with,fgets($fil));
	$myvar=preg_replace_callback($regex,create_function('$matches','return "\"".$matches[1]."\",\"".$matches[2]."\",\"".$matches[3]."\",\"".$matches[4]."\"\r";'),$myrow);
	echo $myvar;
}
}while(next($get_file));
?>

 

The regex is loose, but here's basically what it's trying to convert:

 

LAST_NAME, FIRST_NAME (MIDDLE_INITIAL )? MM/DD/YYYY $#,###.## CITY STATE\n

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.