Jump to content

[SOLVED] Trouble with preg_replace and a lookup interpolated into the replace string.


dbmathis

Recommended Posts

Hello phpfreaks!

 

This works..

 

for( $i=0; $i<sizeof( $narray ); $i++ ) {
    $narray[$i] = preg_replace("/(\w{3})-(\d{2})-(\d{4})/", "$3$1$2", $narray[$i]);
}

 

But this doesn't..

 

$month = array(
               'Jan' => '01',
               'Feb' => '02',
               'Mar' => '03',
               'Apr' => '04',
               'May' => '05',
               'Jun' => '06',
               'Jul' => '07',
               'Aug' => '08',
               'Sep' => '09',
               'Oct' => '10',
               'Nov' => '11',
               'Dec' => '12',
               );

for( $i=0; $i<sizeof( $narray ); $i++ ) {
    $narray[$i] = preg_replace("/(\w{3})-(\d{2})-(\d{4})/", "$3$month[$1]$2", $narray[$i]);
}

 

I get this error with the code that doesn't work...

 

[sun Jul 19 01:07:05 2009] [error] [client 12.5.151.3] PHP Parse error:  syntax error, unexpected '$', expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/sthoma45/public_html/bulletins/list-bulletins.php on line 41, referer: http://217.110.71.74/~sthoma45/bulletins/

 

Can someone steer me in the right direction?

 

Best Regards

 

David

Variable names cannot start with numbers. Maybe PHP is treating your regex back references as variables.

 

You mean to say that maybe PHP is treating back reference $1 that's placed inside of $month[] as a normal variable? Perhaps it is, but if that's the case what's the most elegant solution?

I don't think you can read from the array like that when using preg_replace,

for example

'\3'.$month['\1'].'\2'

would look for

$month['\1']

and not

$month['Jan']

 

I would recommend using a callback,

 

like this

<?php
for( $i=0; $i<sizeof( $narray ); $i++ ) {
    $narray[$i] = preg_replace_callback("/(\w{3})-(\d{2})-(\d{4})/", "convertDate", $narray[$i]);
}

function convertDate($match)
{
	global $month;
	return $match[3].$month[$match[1]].$match[2];
}
?>

 

EDIT:

 

In your previous code instead of using "$3$1$2" use "\3\1\2"

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.