Any better way to replace with a previous reg_expression ?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
wallbrick
Forum Newbie
Posts: 1
Joined: Wed Apr 23, 2008 10:36 pm

Any better way to replace with a previous reg_expression ?

Post by wallbrick »

Hi all, this is my first post, so bear with me if it's against whatever rules.

First thing first, the text to be processed has the following pattern:

a1=x1 b1=y1
a1=x2 b1=y2
a1=x3 b1=y3
.....

where x1, x2, x3 ... and y1, y2, y3... are all random strings without white characters or '=', a1 and b1 are both fixed strings never change.

I want to replace y1, y2, y3 ... with corresponding x1, x2, x3...

Here is what I figured out. Although it works, it doesn't look nice. Anyone has a better idea ? Thanks.

$strPattern = '/'.reg_quote('/a1=/','/').'(\S+)\s+'.reg_quote('b1=','/').'(\S+)/iU';

$strTruncated = $stringToBeProcessed;

while( preg_match( $strPattern, $strTruncated, $matches ) )
{
$strWanted .= preg_replace( '/'.reg_quote($matches[2],'/').'/iU', $matches[1], $matches[0] );
$strDeleted = '/'.preg_quote($matches[0],'/').'/iU';
$strTruncated =
preg_replace( $strDeleted, '', $strTruncated,1 );
}
$strWanted .= $strTruncated;


so basically it's just to read one line at a time and do replace and delete that line and go on to the next line till the end.

for a large $stringToBeProcessed, it seems to take a lot of time to finish, at least on my computer.
Post Reply