There is a task to delete the last line feed \n from the text if there are no characters behind it, or its own spaces followed by it, if there are no other characters except the spaces until the end of the text.
I use preg_replace () and the regular expression %\n\x20*$%
The test gives the expected behavior when replacing:
$text = "abcd\n \n "; var_dump(preg_replace('%\n\x20*$%', '', $text, -1, $count), $count); var_dump(preg_replace('%\n\x20*$%', '', $text, 1, $count), $count); Result of work:
string 'abcd ' (length=10) int 1 string 'abcd ' (length=10) int 1 The test gives an unexpected result:
$text = "abcd\n \n"; var_dump(preg_replace('%\n\x20*$%', '', $text, -1, $count), $count); var_dump(preg_replace('%\n\x20*$%', '', $text, 1, $count), $count); Result of work:
string 'abcd' (length=4) <== замена прошла два раза, int 2 <== вместо одного как ожидалось string 'abcd ' (length=5) <== "съежены" пробелы до символа перевода строки, int 1 <== даже при выполнении всего 1ой замены Question : What is my mistake?
PS A similar regular expression for the beginning of the text works as expected in all cases.
rtrim()no limit on the number of operations. - Visman