michaellunsford Posted May 26, 2007 Share Posted May 26, 2007 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 https://forums.phpfreaks.com/topic/53077-solved-unexpected-results-from-preg_replace_callback/ Share on other sites More sharing options...
michaellunsford Posted May 27, 2007 Author Share Posted May 27, 2007 I switched to preg_match and now I'm getting nothing. Is it possible that the regex between php and my test environment are different enough to cause the problem? Link to comment https://forums.phpfreaks.com/topic/53077-solved-unexpected-results-from-preg_replace_callback/#findComment-262640 Share on other sites More sharing options...
michaellunsford Posted May 28, 2007 Author Share Posted May 28, 2007 the \$ was giving me trouble -- I couldn't combine the \$ with anything else inside the brackets. So here's the fix: /[^a-z]+?([^0-9]+)([^\$]+)([\$][0-9,\.]+)[^a-z]+([a-z ]+)/i Link to comment https://forums.phpfreaks.com/topic/53077-solved-unexpected-results-from-preg_replace_callback/#findComment-263026 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.