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

Link to comment
Share on other sites

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.