Limit characters in preg_replace

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

Moderator: General Moderators

Post Reply
mzfp2
Forum Contributor
Posts: 137
Joined: Mon Nov 11, 2002 9:44 am
Location: UK
Contact:

Limit characters in preg_replace

Post by mzfp2 »

Hi,

I'm using a regular expression to search and replace template comments in html files, below is the snippet of code responsible :

Code: Select all

$string = preg_replace("#<!--%(.*?:)(\d+)%-->#", "$1", $string);
The code above replaces all

Code: Select all

<!--%name:8%-->
wiith just name. Soo the result would be

Code: Select all

<!--%name%-->
.

What I want to do is use the second match parameter (\d+) to limit the number of charaters name is rpelaced with.

For instance :

Code: Select all

<!--%Description:5%-->
should translate to

Code: Select all

<!--%Descr%-->
is this possible?

Any help would be appreciated.

Musaffar
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

using preg_replace_callback(), certainly.
mzfp2
Forum Contributor
Posts: 137
Joined: Mon Nov 11, 2002 9:44 am
Location: UK
Contact:

Post by mzfp2 »

Hi Feyd,

Thanks for your reply, I have taken a look at the function, i'm afraid II dont understand much of it, I'm not very good at reg exp, and it took me quite a while to come up with expression above !

Could anyone help me with this expression?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Your expression is generally fine. You need to create a function that takes the information from the match information and generates the desired output using substr(). That's what preg_replace_callback() is used for.
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

In a nutshell, preg_replace_callback, rather than flat out replacing matched text with new text, will call the function you pass to it in order to determine what to replace the text with.
Post Reply