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
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
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

Add a Patch

Pull Requests

Add a Pull Request

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-2024 The PHP Group
All rights reserved.
Last updated: Tue May 07 02:01:30 2024 UTC