1

I know what needs to be done, but have been unsuccessful with the correct regex.

What is the regular expression I should use in preg_replace() to find tabs inside all quoted strings and replace with a single space?

any help would be much appreciated.

Example:

$string = '"Foo\tMan\tChoo"'

preg_replace($expression_string, ' ',$string);

echo $string;//desired result---->'"Foo Man Choo"'

I think this question is not a duplicate

answer : you will need to repeat preg_replace as many time as the max of \t you expect in a field (never could be bothered comming up with a more generic solution : it is usually possible to use this one)

also make sure every line ends with a tab (otherwise the last field will not be processed)

then you need to repeat replacement starting with the max possible number of \t (2 in the example)

$string = '"Foo'."\t".'Man'."\t".'Choo"'."\t".'boo'."\t".'"Foo'."\t".'Man"'."\t";

$string = preg_replace('/"([^"]*)'."\t".'([^"]*)'."\t".'([^"]*)"'."\t".'/','"$1_$2_$3"'."\t",$string);
$string = preg_replace('/"([^"]*)'."\t".'([^"]*)"'."\t".'/','"$1_$2"'."\t",$string);

echo $string;
v2belleville
  • 189
  • 14
  • Why would use regex for something a `str_replace` can do? `str_replace(CHR(9), CHR(32), $string);` – ficuscr Aug 23 '17 at 17:47
  • Because I'm working with tab delimited files, if i do a straight str_replace, the delimiters will die. – user2599674 Aug 23 '17 at 17:49
  • Not sure I follow that. The functions work in the same way. One is a native string function, the other `pcre`. Back in the day more relevant as `ereg` was not very performant, but I feel you should still use right tool for the job. – ficuscr Aug 23 '17 at 17:52
  • @ficuscr I do not think this question is duplicate of mentioned questioned because the problem here is to do a context sensitive replace : only \t _inside_ quoted fields should be replaced - see edit for the answer I would like to submit – v2belleville Sep 27 '17 at 13:20
  • Sorry. I don't think I saw that aspect of the question when commenting before. Does the suggested "Replace all occurrences of char inside quotes on PHP" not answer it? – ficuscr Sep 27 '17 at 17:27

0 Answers0