Bug #64251 [Nab]: preg_replace non-obvious behavior

From: Date: Wed, 20 Feb 2013 15:22:32 +0000
Subject: Bug #64251 [Nab]: preg_replace non-obvious behavior
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-177265@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=64251&edit=1

 ID:                 64251
 Updated by:         laruence@php.net
 Reported by:        root at microsoft dot com
 Summary:            preg_replace non-obvious behavior
 Status:             Not a bug
 Type:               Bug
 Package:            Scripting Engine problem
 Operating System:   all
 PHP Version:        5.4.11
 Block user comment: N
 Private report:     N

 New Comment:

return preg_replace('/\{(.+?)\}/',
			$this->rand(explode('|', '\\1')),
			$text);

is same as:
return preg_replace('/\{(.+?)\}/',
			'\1',
			$text);

for $this->rand(explode('|', '\\1')) will be called first and the result as
the 
second argument to preg_replace.

so I see no problem here..


Previous Comments:
------------------------------------------------------------------------
[2013-02-20 15:15:18] johannes@php.net

Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to
report
a bug at http://bugs.php.net/how-to-report.php

My::rand() will be called before calling preg_replace. The function you are looking for is
preg_replace_callback.

------------------------------------------------------------------------
[2013-02-20 14:30:11] root at microsoft dot com

Description:
------------
Behavior of preg_replace is non-obvious, if second argument is function call.

Test script:
---------------
class My{
	function prepare($text){
		return preg_replace(
			'/\{(.+?)\}/',
			$this->rand(explode('|', '\\1')),
			$text
		);
	}
	private function rand(array $values){
		return $values[rand(0, sizeof($values)-1)];
	}
}

echo (new My)->prepare('i choose {ps3|games}');

Expected result:
----------------
i choose ps
or
i choose games

Actual result:
--------------
i choose ps3|games


------------------------------------------------------------------------



-- 
Edit this bug report at https://bugs.php.net/bug.php?id=64251&edit=1


Thread (3 messages)

« previous php.bugs (#177265) next »