skip to Main Content

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

2

Answers


  1. $input = "222t55555t9thellotbyebyet444";
    
    $parts = explode("t", $input);
    $parts[2] = 2;
    $output = implode("t", $parts);
    
    var_dump($output);
    

    Or:

    $input = "222t55555t9thellotbyebyet444";
    
    $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.

    Login or Signup to reply.
  2. 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 = "222t55555t9thellotbyebyet444";
    $newInt = 2;
    var_export(
        preg_replace("/t[^t]+tKd+/", $newInt, $string, 1)
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search