Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_replace() ignores the count parameter?

Tags:

php

As given here str_replace() count parameter should stop if certain replacements are done. Right?

Here is my code:

define("PLACEHOLDER", "INSERT INTO `listings` VALUES (NULL, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');".PHP_EOL);
$r = (4 - count($_POST['ad']));
print count($_POST['ad'])."\n";
print $r;
$pf_args = str_replace("'%s', ", "", PLACEHOLDER, $r);
print $pf_args;

Now I double-checked everything that $r = 1 in one my test and to be doubly sure count($_POST['ad']) is 3. Still, str_replace completely ignores count parameter and replaces all occurances to give:

INSERT INTO `listings` VALUES (NULL, '%s');

This is driving me insane. Having seen so much anti-php talks, such eccentric behaviour(s) mkes me feel that they are bugs or another one of those weird magic it possesses.

like image 206
Shubham Avatar asked Dec 28 '22 01:12

Shubham


1 Answers

I believe $count is used to check how many replacements were performed (for example, if you printed $count after using str_replace(), you would get 10).

You could do what you want to do by using preg_replace() with a little regex. Please see: How to use str_replace() to remove text a certain number of times only in PHP?

like image 165
Tushar Avatar answered Jan 08 '23 17:01

Tushar