aron n
aron n

Reputation: 597

how do I remove numbers from this comma seperated texts?

web,search,web2.0,1,seo,networking,social
web,search,web2.0,3,seo,networking,social
web,search,web2.0,4,seo,networking,social

How do I remove 1, 3 and 4 from above lines??

Upvotes: 0

Views: 133

Answers (5)

Vivek Goel
Vivek Goel

Reputation: 24160

I am assuming each line is a string

$mystring="web,search,web2.0,1,seo,networking,social";
$temp = explode(",", $mystring);
$mystring="";
for($i=0;$i<count($temp);$i++) {
    if(is_int($temp[$i])==false)
$mystring+=$temp[$i];
if($i <count($temp)-1)
$mystring+=",";
}

Upvotes: 0

Brad Christie
Brad Christie

Reputation: 101614

var_dump(
  implode(
    ',',
    array_filter(
      explode(',',$e),
      create_function('$a','return !is_numeric($a);')
    )
  )
);

results in:

string(39) "web,search,web2.0,seo,networking,social"
string(39) "web,search,web2.0,seo,networking,social"
string(39) "web,search,web2.0,seo,networking,social"

The breakdown:

  • expode()
    Break the array in to tokens, separated by commas.
  • array_filter()
    Take out the elements you don't want (the numbers)
  • create_function()
    Lazy-man's way of making a function to do the filtering (each element is passed to be decided if it stays or goes)
  • implode
    Opposite of explode

Upvotes: 2

With regular expression you can replace ",[0-9]*,?" by "," maybe

Upvotes: 2

Jonas Schmid
Jonas Schmid

Reputation: 5491

Is it always the same format?

$string = ...;
$tab = explode(',', $string);
unset($tab[3]);
$string = implode(',', $tab);

Upvotes: 0

Will Shaver
Will Shaver

Reputation: 13089

PHP has a built in csv parser: http://php.net/manual/en/function.fgetcsv.php

I'd recommend using the parser and then writing your data back out using fputcsv().

Upvotes: 1

Related Questions