Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

preg_replace question 1

Status
Not open for further replies.

jamesp0tter

Programmer
Feb 20, 2003
119
0
0
PT
Hello,

I have the following code:
Code:
<!--TestBegin12--> sjgidshgifdjhsdh <!--TestEnd12-->
<!--TestBegin22--> ssrvytybsgfhgfjh <!--TestEnd22-->
<!--TestBegin47--> fdhsfdjdfyhhsjfj <!--TestEnd47-->
<!--TestBegin2467--> asfsvffdjhsdh <!--TestEnd2467-->
and I need to match them with a preg_replace function...

At first, I only had one
Code:
<!--TestBeginXXXXX--> ??????????????? <!--TestEndXXXXX-->
at a time, so
Code:
$result = preg_replace("#<!--TestBegin(.+?)-->(.+?)<!--TestEnd(.+?)-->#",'[Test=\\1]',$result);
worked fine.

But now that I have more than one, that preg_replace matches the first line's TestBeginXX and the last line's TestBeginXX (being this last XX different from the first one).

I would need some preg_replace pattern that would work like this: match first <!--TestBeginXX--> occurence, and then the <!--TestEndXX--> right after it, so that the XX's would match!

Anyone can help ?
Thanks in advance!

jamesp0tter,
mr.jamespotter@gmail.com

p.s.: sorry for my (sometimes) bad english :p
 
Take a look at the pattern modifiers for PCREs. You need to add the "ungreedy" modifier to your match expression:
Code:
$result = preg_replace("#<!--TestBegin(.+?)-->(.+?)<!--TestEnd(.+?)-->#[red]U[/red]",'[Test=\\1]',$result);
 
I recommend a different approach.
PCRE regex allow you to have back references. You can access content captured earlier in the expression with the same back reference syntax you use for replacements:
Code:
$test = "
<!--TestBegin12--> sjgidshgifdjhsdh <!--TestEnd12-->
<!--TestBegin22--> ssrvytybsgfhgfjh <!--TestEnd22-->
<!--TestBegin47--> fdhsfdjdfyhhsjfj <!--TestEnd47-->
<!--TestBegin2467--> asfsvffdjhsdh <!--TestEnd2467-->";
$pattern = "#<!--TestBegin(.+?)-->(.+?)<!--TestEnd\\1-->#";
$new = preg_replace($pattern,'[Test=\\1]',$test);
print($new);
The \\1 inserted after the TestEnd will make sure the numbers match.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top