preg_replace question???

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

preg_replace question???

Post by alex.barylski »

I have the following code:

Code: Select all

func_name\('param1'\s*,\s*'(.+)'\)
I am using preg_replace()

I am trying to use the ABOVE regex to localize the second parameter of a funciton call...and replace the string text, but I"m not sure this is possible without rewritting the entire function call???

Note: param1 is fixed and my only concern is to locate the text in between (.+) and replace ONLY it with another variable...

Is this possible or do I have to rewrite the entire function call...basically everythiing which i've matched with teh above regex???

Cheers :)
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

try this for your pattern:

Code: Select all

func_name\('param1'\s*,\s*'(.*?)'\)
that will match anything between your "'" and "'" for your second argument.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

Burrito wrote:try this for your pattern:

Code: Select all

func_name\('param1'\s*,\s*'(.*?)'\)
that will match anything between your "'" and "'" for your second argument.
It's not matching i'm having the problem with...everything between single quotes is located just fine...

What I need to do is REPLACE ONLY WHAT is inside the (.+) and nothing more...

But I need the whole regex, otherwise I will likley locate other strings which don't need to be replaced....

Follow me?

Cheers :)
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

ahh...so you're having problems with preg_replace() itself then?

I think I understand...try this:

Code: Select all

<?
$string = "func_name('param1','param2')";
$pattern = "/(func_name\('param1'\s*,\s*').*?('\))/";
$string = preg_replace($pattern,"\\1param4\\2",$string);
echo $string;
?>
Post Reply