1

I am trying to mass replace some keywords in a csv file, for example I have a list of keywords cat,mouse,dog with i would like to replace with something,else,here , I am currently using this http://phpcsv.sourceforge.net/phpcsv-1.0.php it is perfect and it says it uses PCRE for replacing values , my question is what do i need to type in the search and replace field to achieve this result ?

XkiD
  • 159
  • 1
  • 14
  • What do you mean? You are replacing them in PHP, so what search and replace fields are you typing it in to? – Jon Feb 24 '13 at 13:22
  • I am using http://phpcsv.sourceforge.net/phpcsv-1.0.php , it has 2 fields for search,replace , i am sorry i am not a coder , i dont understand many things – XkiD Feb 24 '13 at 13:32
  • would be easier with [`str_replace`](http://www.php.net/manual/en/function.str-replace.php) and give it arrays for the pattern and replacement. – Jon Feb 24 '13 at 13:33
  • from what I see in this php script it does with preg_replace , but i do not know how to input my list – XkiD Feb 24 '13 at 13:35
  • I can't see the source for that script, but if that's all you're doing to the csv file, then `str_replace(array('cat','mouse','dog'), array('cat2','mouse2','dog2'), $csv_text);` would easily do it for you. – Jon Feb 24 '13 at 13:38
  • http://sourceforge.net/projects/phpcsv/files/phpcsv-1.0.php/download the source is here... – XkiD Feb 24 '13 at 13:51
  • I have no desire to download it and go through that code, especially if you aren't using the code yourself. If you absolutely need to do this in that tool, look at the answer below. Otherwise, you can use `str_replace` to do it in your own code. – Jon Feb 24 '13 at 13:56

1 Answers1

1

You could use

Search (?<=^|,)(cat|mouse|dog)(?=,|$) Replace ${1}2

The ${1} is used to reference the string captured by the () in the Search field.
Normally you could just use $1, but because it is followed immediately by 2, the 1 needs to be enclosed in {}.

If the values may be enclosed in " add "? before and after (cat|mouse|dog).

(?<=^|,) means looking behind there must be the start of a line or a comma.
(?=,|$) means looking ahead there must be a comma or the end of a line.

If the replacements are different for each keyword, I think you would have to do each separately, e.g.

Search (?<=^|,)cat(?=,|$) Replace hamster

Alternatively, if using your own code you could make all the replacements in one go by passing arrays as arguments to preg_replace.

MikeM
  • 13,156
  • 2
  • 34
  • 47
  • but wat if i want something like cat,mouse,dog and replacing with hamster,elephant,octopus , thats what i wanted but i mistakenly wrote cat2 etc. – XkiD Feb 24 '13 at 17:43