Add new lines to string to replace in php

In PHP, you can use the str_replace() function to replace a substring with a new string. Here's an example:

$string = "Hello, world!";
$newString = str_replace("world", "PHP", $string);
echo $newString; // Output: "Hello, PHP!"

In this example, the str_replace() function replaces the substring "world" with the new string "PHP" in the original string.

If you want to add new lines to the string, you can use the str_replace() function with an array of substrings to replace and an array of new strings to add. Here's an example:

$string = "Hello, world! This is a test.";
$newLines = array("\n", " ");
$newStrings = array("New line 1", "New line 2");
$string = str_replace($newLines, $newStrings, $string);
echo $string; // Output: "Hello, world! New line 1 This is a test. New line 2"

In this example, the str_replace() function replaces the substrings "\n" and " " with the new strings "New line 1" and "New line 2", respectively.

Alternatively, you can use the preg_replace() function with a regular expression to add new lines to the string. Here's an example:

$string = "Hello, world! This is a test.";
$string = preg_replace('/\s+/', "\n", $string);
echo $string; // Output: "Hello, world!\nThis is a test.\n"

In this example, the preg_replace() function replaces one or more whitespace characters (\s+) with a new line character (\n) in the original string.

Note that the str_replace() function is case-sensitive, while the preg_replace() function is not. If you need to perform a case-insensitive replacement, you can use the preg_replace() function with the i modifier, like this:

$string = "Hello, world! This is a test.";
$string = preg_replace('/\s+/', "\n", $string, PREG_REPLACE_ORDER, 'i');
echo $string; // Output: "Hello, world!\nThis is a test.\n"