Page 1 of 1

Limit characters in preg_replace

Posted: Sun Nov 12, 2006 8:59 am
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

Posted: Sun Nov 12, 2006 9:08 am
by feyd
using preg_replace_callback(), certainly.

Posted: Sun Nov 12, 2006 9:56 am
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?

Posted: Sun Nov 12, 2006 10:16 am
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.

Posted: Sun Nov 12, 2006 12:03 pm
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.