diff --git a/src/StringUtil.php b/src/StringUtil.php index 4dcdfe4..11daa28 100644 --- a/src/StringUtil.php +++ b/src/StringUtil.php @@ -105,6 +105,14 @@ public static function removeZeroWidthCharacters(string $input): string return \Safe\preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $input); } + /** Replaces line breaks with spaces and collapses consecutive whitespace into one space. */ + public static function replaceLineBreaksWithSpaces(string $input): string + { + $withoutLineBreaks = str_replace([self::WINDOWS_NEWLINE, "\r", "\n"], ' ', $input); + + return \Safe\preg_replace('/\s+/', ' ', $withoutLineBreaks); + } + /** Convert string that could be in different UTF encodings (UTF-8, UTF-16BE, ...) to UTF-8. */ public static function toUTF8(string $string): string { diff --git a/tests/StringUtilTest.php b/tests/StringUtilTest.php index 442c7f3..2a64f7a 100644 --- a/tests/StringUtilTest.php +++ b/tests/StringUtilTest.php @@ -97,6 +97,14 @@ public function testRemoveZeroWidthCharacters(): void ); } + public function testReplaceLineBreaksWithSpaces(): void + { + self::assertSame( + 'Befund: unauffällig Empfehlung: Kontrolle', + StringUtil::replaceLineBreaksWithSpaces("Befund:\r\nunauffällig\n\nEmpfehlung: \rKontrolle") + ); + } + public function testUTF8(): void { $expectedUTF8 = 'test';