Amy Neville
Amy Neville

Reputation: 10581

Remove excess commas from string PHP

I've filtered some keywords from a string, to remove invalid ones but now I have a lot of extra commas. How do I remove them so I go from this:

,,,,,apples,,,,,,oranges,pears,,kiwis,,

To this

apples,oranges,pears,kiwis

This question is unique because it also deals with commas at the start and end.

Upvotes: 7

Views: 5014

Answers (4)

Professor Abronsius
Professor Abronsius

Reputation: 33813

How about using preg_replace and trim?

$str=',,,,,apples,,,,,,oranges,pears,,kiwis,,';
echo trim( preg_replace('@,{2,}@',',',$str), ',');

Upvotes: 0

devpro
devpro

Reputation: 16117

You can also achieve this by using preg_split and array_filter.

$string = ",,,,,apples,,,,,,oranges,pears,,kiwis,,";
$keywords = preg_split("/[\s,]+/", $string);
$filterd = array_filter($keywords);
echo implode(",",$filterd);

Result:

apples,oranges,pears,kiwis

Explanation:

  1. split with comma "," into an array
  2. use array_filter for removing empty indexes.
  3. implode array with "," and print.

From Manual: preg_split — Split string by a regular expression (PHP 4, PHP 5, PHP 7)

Upvotes: 4

Franz Gleichmann
Franz Gleichmann

Reputation: 3568

$string = preg_replace("/,+/", ",", $string);

basically, you use a regex looking for any bunch of commas and replace those with a single comma. it's really a very basic regular expression. you should learn about those!

https://regex101.com/ will help with that very much.

Oh, forgot: to remove commas in front or after, use

$string = trim($string, ",");

Upvotes: 19

Pupil
Pupil

Reputation: 23958

Use PHP's explode() and array_filter() functions.

Steps:

1) Explode the string with comma.

2) You will get an array.

3) Filter it with array_filter(). This will remove blank elements from array.

4) Again, implode() the resultant array with comma.

5) You will get commas removed from the string.

<?php
$str = ',,,,,apples,,,,,,oranges,pears,,kiwis,,';
$arr = explode(',', $str);
$arr = array_filter($arr);
echo implode(',', $arr);// apples,oranges,pears,kiwis 
?>

Upvotes: 8

Related Questions