Home » Php » PHP removing a certain string in a string once

PHP removing a certain string in a string once

Posted by: admin February 25, 2020 Leave a comment


I recently have played around with the use of preg_replace in PHP to specifically remove a string once.

However I have a list of numbers (345, 346 and wanting to remove “, 346” for example) and I have kept on running into the same problem how it removes the whole string and leaves it empty.

Desired results are

345, 346
Removing ", 346"
Turns to
And also
345, 346, 347 removing ", 346"
Turns to 
345, 347


$oldpost = ", ".$_GET['id'];

$newposts = preg_replace($oldpost, "", $row['posts']);

I tried this previously and haven’t found anything that seems to do a better job.

How to&Answers:

In your code, you have

$newposts = preg_replace($oldpost, "", $row['posts']);

where you are actually giving the entire string itself to be replaced. Hence, it gives you an empty string because your 2nd parameter is an empty string.

You can match the exact 346(if it’s present) with an optional matching of a , and replace them with empty string. So your regex would look like




$oldpost = "345,346,347";
$newposts = preg_replace("/(,?\s*346(\s|,|\b))?/", "$2", $oldpost);
echo $newposts,PHP_EOL;

Demo: https://3v4l.org/MeSeK

Note that above approach works fine, but the best way to solve this problem is to explode the comma separated string and unset the location in the array where have the 346 and implode it back again.



$oldpost = "345,346,347";
$posts = explode(",",$oldpost);

$index = array_search(346,$posts);

if($index !== false){

$new_post = implode(",",$posts);

echo $new_post;

Demo: https://3v4l.org/qvSEN

Note that if there are multiple occurrences of 346, you can use a simple foreach to unset them.


Documentation is here for preg_replace:

Try adding a value for the “limit” parameter.

The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).