Home > database >  PHP - How can I replace after the 2nd occurrence of a tab
PHP - How can I replace after the 2nd occurrence of a tab

Time:10-27

I have a string like this, with several tabs in it. I need to replace a single digit, it will always be the digit after the 2nd tab. The numbers before that could be different lengths, so I can't simply replace after 10 digits or something like that. It has to be after the 2nd tab. the new string will be exactly the same except for that one digit. example...

222[TAB]55555[TAB]9[TAB]hello[TAB]byebye[TAB]444

change to

222[TAB]55555[TAB]2[TAB]hello[TAB]byebye[TAB]444

CodePudding user response:

$input = "222\t55555\t9\thello\tbyebye\t444";

$parts = explode("\t", $input);
$parts[2] = 2;
$output = implode("\t", $parts);

var_dump($output);

Or:

$input = "222\t55555\t9\thello\tbyebye\t444";

$parts = str_getcsv($input, "\t");
$parts[2] = 2;
$output = implode("\t", $parts);

var_dump($output);

Output:

string(28) "222 55555   2   hello   byebye  444"

str_getcsv() being more useful if your data includes encapsulated strings, line breaks, etc.

CodePudding user response:

To replace the integer value after the second occurring tab, match the first occuring tab, then one or more non-tab characterss, then the second tab, then forget all of those matched characters with \K, then match the one or more digit number. Replace the matched number with the new desired value. Limit the number of replacements to one.

This is more direct than exploding or parsing the entire string just to change one value.

Code: (Demo)

$string = "222\t55555\t9\thello\tbyebye\t444";
$newInt = 2;
var_export(
    preg_replace("/\t[^\t] \t\K\d /", $newInt, $string, 1)
);
  • Related