substr_replace either creates an infinite loop or doesn’t replace substrings

I’ve been having this issue lately.

So basically I have a string that I get like this:

$contents = file_get_contents("system.po");

And it looks like this:

msgctxt "views.view.fra_vacancies:label:display:default:display_title:display_options:exposed_form:options:submit_button:reset_button_label:exposed_sorts_label"
msgid "Sort by"
msgstr ""

msgctxt "views.view.fra_vacancies:label:display:default:display_title:display_options:exposed_form:options:submit_button:reset_button_label:exposed_sorts_label:sort_asc_label"
msgid "Asc"
msgstr ""

(but with many entries like the above)

And I also have a table like this called $finalArray (with many entries as well):

[1041] => Array
        (
            [0] => Sort by name
            [1] => Ταξινόμηση κατά όνομα
        )
[1042] => Array
        (
            [0] => Country
            [1] => Χώρα
        )

What I do is going to each msgid in my file-string with strpos and check the value (for example “Sort By”), then i search if the value exists in my table (at [0] index) and then I move to msgstr with strpos and I replace the whole line with a string which contains the translation from my table (at [1] index)

Here is the code:

$lastPos = 0;
//while loop to go to each 'msgid' in my file-string
while (($lastPos = strpos($contents, 'msgid', $lastPos))!== false) {
//here i get the whole 'msgid' line
  $startOfLine = strrpos($contents, "n", ($lastPos - $len));
  $endOfLine = strpos($contents, "n", $lastPos);
  $sourceLine = substr($contents, $startOfLine, ($endOfLine - $startOfLine));

//here i change the pos and i go to the next 'msgstr' and i get the whole line
  $lastPos = strpos($contents, 'msgstr', $lastPos);
  $start = strrpos($contents, "n", ($lastPos - $len));
  $end = strpos($contents, "n", $lastPos);
  $transLine = substr($contents, $start, ($end - $start));

//here i find the value that matches from my array and i try to replace the substring
  foreach ($finalarray as $key => $value) {
    if (substr_count_array($sourceLine, [$value[0], 'msgid']) == 2){
      $rstring = 'msgstr ' . '"' . $value[1] . '"';
//debugged and checked that $sourceLine and $transLine are correct but is the issue * 
      $contents = substr_replace($contents, $rstring, $start, 0);
      break;
    }
  }
}
//just a function that checks if more strings exist in a substring
function substr_count_array( $haystack, $needle ) {
  $count = 0;
  foreach ($needle as $substring) {
       $count += substr_count( $haystack, $substring);
  }
  return $count;
}

*The issues is that when i use:

$contents = substr_replace($contents, $rstring, $start, 0);

I get an infininte loop and when I assing the result of substr_replace to a different variable (for example $contentsNew) and I echo it, my strings aren’t replaced.

Thank you for your time.