php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #64251 preg_replace non-obvious behavior
Submitted: 2013-02-20 14:30 UTC Modified: 2013-02-20 15:22 UTC
From: root at microsoft dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.4.11 OS: all
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: root at microsoft dot com
New email:
PHP Version: OS:

 

 [2013-02-20 14:30 UTC] 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

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2013-02-20 15:15 UTC] 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 15:15 UTC] johannes@php.net
-Status: Open +Status: Not a bug
 [2013-02-20 15:22 UTC] laruence@php.net
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..
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Fri Jul 04 15:01:36 2025 UTC