Jump to content

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


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"

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.