php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #66765 strtr key replacing order
Submitted: 2014-02-24 22:26 UTC Modified: 2017-10-26 17:22 UTC
Votes:3
Avg. Score:3.7 ± 0.9
Reproduced:3 of 3 (100.0%)
Same Version:2 (66.7%)
Same OS:2 (66.7%)
From: pawel dot ulewicz at gmail dot com Assigned:
Status: Open Package: Strings related
PHP Version: 5.5.9 OS: Windows 7
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2014-02-24 22:26 UTC] pawel dot ulewicz at gmail dot com
Description:
------------
It looks like strtr function replaces strings in the following order:

1) first occurences first,
2) longest keys first.

I don't think it's a bad thing, but it doesn't work as documented. Here's the quation from the official docs:

"The longest keys will be tried first"

So, it's either a documentation problem or a bug.


Test script:
---------------
<?php

// expecting 'bcde' to be replaced first
echo strtr('abcdef', ['abc'=> '1', 'bcde'=> '2']) . "\n";

// the following two are replaced as expected, just to give more info
echo strtr('abcdef', ['a'=> '2', 'abc'=> '1']) . "\n";
echo strtr('abcdef', ['abcd'=> '2', 'abc'=> '1']) . "\n";


Expected result:
----------------
a2f
1def
2ef


Actual result:
--------------
1def
1def
2ef


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2014-02-28 11:45 UTC] ab@php.net
-Status: Open +Status: Analyzed -Assigned To: +Assigned To: ab
 [2014-02-28 11:45 UTC] ab@php.net
I can confirm that, it's across platforms

- strtr('abcdef', ['a'=> '1', 'bcde'=> '2']) works
- strtr('abcdef', ['abc'=> '1', 'bcde'=> '2']) bug
 [2016-10-12 15:40 UTC] cmb@php.net
It seems to me this is a documentation issue. strtr() walks the
string from left to right, continously replacing the longest
matching sequence.
 [2017-10-24 05:46 UTC] kalle@php.net
-Status: Analyzed +Status: Assigned
 [2017-10-26 17:22 UTC] ab@php.net
-Status: Assigned +Status: Open -Assigned To: ab +Assigned To:
 
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Mon Sep 16 14:01:28 2019 UTC