NYCPHP Meetup

NYPHP.org

[nycphp-talk] ereg_replace() behavior

Dan Cech dcech at phpwerx.net
Thu Jul 10 10:16:25 EDT 2008


Anirudh Zala wrote:
> I am facing a strange behavior of PHP's ereg_replace() function. Here is 
> scenario:
> 
> Problem:
> 
> Removing "__" (2 continuous underscores) and Capitalizing character that 
> immediately follows "__" from a string. In our example our string 
> is 'ss__name' and expected output should be 'ssName'.
> 
> Solution:
> 
> Tried following code using function "ereg_replace()" but character is not 
> getting capitalized:
> 
> echo ereg_replace('__([:alnum:]{1})',strtoupper('\1'),'ss__name');
> 
> Outputs:
> 
> "ssname" instead of "ssName"

The strtoupper is being executed before ereg_replace, and doesn't have 
any effect on the string '\1' because it doesn't contain any alphabet 
characters.

You need to use the /e modifier for preg_replace()

echo preg_replace('/__([a-z0-9])/ie','strtoupper(\'$1\')','ss__name');

> Contrary to above explanation, following code works properly (I just used 
> different function instead of "strtoupper"):
> 
> echo ereg_replace('__([:alnum:]{1})',str_repeat('\1',5),'ss__name');
> 
> Outputs:
> 
> "ssnnnnname" as expected.

This is executed as:

echo ereg_replace('__([:alnum:]{1})','\1\1\1\1\1','ss__name');

Dan



More information about the talk mailing list