php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #76944 4th parameter to str_replace / str_ireplace does not work
Submitted: 2018-09-28 09:54 UTC Modified: 2018-09-28 10:12 UTC
From: een dot meel dot of dot geen dot meel at gmail dot com Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 7.0.32 OS: any
Private report: No CVE-ID: None
 [2018-09-28 09:54 UTC] een dot meel dot of dot geen dot meel at gmail dot com
Description:
------------
str_replace and str_ireplace have a 4th argument that should allow one to limit the amount of replacements.

However, this 4th replacement does not work.
Furthermore, the 4th replacement MUST be a variable that is passed by reference for some reason??

Test script:
---------------
<?php
error_reporting(1);

echo str_replace('Hel', '', 'HelHello people! Helloooo! helloo!', 1)."\n";
echo str_ireplace('hel', '', 'HelHello people!!! Helloooo! helloo!', 1)."\n";

$ct = 1;
echo str_replace('Hel', '', 'HelHello people! Helloooo! helloo!', $ct)."\n";
echo str_ireplace('hel', '', 'HelHello people!!! Helloooo! helloo!', $ct)."\n";

Expected result:
----------------
Hello people! Helloooo! helloo!
Hello people! Helloooo! helloo!
Hello people! Helloooo! helloo!
Hello people! Helloooo! helloo!

Actual result:
--------------
(Multiple runs, obviously)

>
PHP Fatal error:  Only variables can be passed by reference in /opt/local/apache2/htdocs/x.php on line 4

>
PHP Fatal error:  Only variables can be passed by reference in /opt/local/apache2/htdocs/x.php on line 5

>
lo people! loooo! helloo!
lo people!!! loooo! loo!

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2018-09-28 10:12 UTC] salathe@php.net
-Status: Open +Status: Not a bug
 [2018-09-28 10:12 UTC] salathe@php.net
> str_replace and str_ireplace have a 4th argument that should allow one to limit the amount of replacements.

This is not the case. The $count argument should be a variable, which will be populated with the number of replacements that happened.

Perhaps you confused it with the $limit argument for functions like preg_replace() and friends.

The following shows that the "a" in "banana" was replaced 3 times:

    $counter = 0;
    $result = str_replace("a", "", "banana", $counter);
    var_dump($result, $counter);
    // string(3) "bnn"
    // int(3)
 [2018-09-28 10:13 UTC] spam2 at rhsoft dot net
it is called count and the documentation clearly states that it GIVES BACK the number of replacements so i wonder from where your idea about limit comes

parameters as reference in PHP are common when you have more than one desired return values or like here give back the modified string and some additional information
 
PHP Copyright © 2001-2018 The PHP Group
All rights reserved.
Last updated: Mon Nov 19 11:01:25 2018 UTC