The preg_replace limit and arrays.

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

Hi, :)

The preg_replace function...

preg_replace(pattern, replacement, subject [, int limit])

How on earth do you get the limit value to work with arrays?

In my code both the pattern and replacement parameters are arrays and I
only want a specified number of replacements to occur.

Can anyone help me find a solution? There must be one out there
somewhere. :-/


Marc :O)

Re: The preg_replace limit and arrays.

Afkamm wrote:

Quoted text here. Click to load it

When you specify a limit, only that number of replacements
occur.  With a limit of 1, preg_replace() tries to replace
each array element in pattern by the corresponding* element
in replacement once; a limit of 2, each element in pattern
by the corresponding one in replacement *twice*; and so on.

* Corresponding meaning the same position, not necessarily
the same index.

Quoted text here. Click to load it

Why would you pass to preg_replace() more patterns than you
want to search for and more replacements than you want to
make?  If the number of elements in your arrays exceeds your
specified number, more replacements will occur than you
want.  Shorten the arrays.


Re: The preg_replace limit and arrays.

Drinkers log, beer date Sat, 05 Mar 2005 16:43:09 GMT. After downing
several pints in comp.lang.php, John Dunlop slurred the following.

Quoted text here. Click to load it

I was under the impression that the limit value would stop the function
after that amount of replacements had been reached. But you're saying
that it only stops the array element it matched being replaced more
than what the limit is?

Quoted text here. Click to load it

I'm trying to write a small mod/hack for the phpBB forum. What the
original code for smiley matching does, is create an array(pattern) of
all the smiley codes and at the same time creates a corresponding array
(replacement) with the html <img> tag code. It then uses the
preg_replace() function to go through the message post replacing any
codes found.

What I'm trying to do is limit the amount of times that smiley code
would be replaced by the corresponding html <img> code. ie. If 10
different smiley codes were used in a message and the limit was 5, then
only the first 5 would be replaced.

Is what I'm trying possible with a small piece of code or is it
something major? As anything large would slow the forum down some what.

Thanks for your reply. :)

Marc :O)

Site Timeline