Reputation: 1543
The code below will replace certain text. Actually I get the $str
data from a text file with file_get_contents
so please imagine there's a new line in the $str
.
$str = 'From: My Name <[email protected]>
To: [email protected]
Message-ID: <[email protected]>';
$old = array("My Name", "To: [email protected]");
$new = array("New Name", "");
echo str_replace($old, $new, $str );
Output:
From: New Name
Message-ID: <[email protected]>
Unfortunately after removing To: [email protected]
, the code will create a line break. How can I use str_replace
without creating new break line?
Upvotes: 0
Views: 479
Reputation: 59691
It doesn't create a new line, it's just left from your str_replace()
.
So if you want to remove every line which only contains new line characters you can use this:
(Here I first replace the $old
with the $new
, after this I explode()
the string by new line characters. Then I use array_map()
combined with trim()
to remove these characters (["", "\t", "\n", "\r", "\0", "\x0B"]
) from every line. Then I remove all remaining empty lines with array_filter()
and at the end I implode()
the string again)
echo $str = implode(PHP_EOL,
array_filter(
array_map("trim",
explode(PHP_EOL, str_replace($old, $new, $str))
)
)
);
Upvotes: 2
Reputation: 465
str_replace
does not add a new line break; it replaces the string with what you supported and you told it to replace the text in the line with an empty string.
The easiest way is to include the line break in your search array:
$old = array("My Name", "To: [email protected]\n");
Upvotes: 1
Reputation: 94662
Like you said you get this from a text file and if what you show is what is in the text file then it is not creating a newline character, it is actually you that is not removing the already existing new line.
Try
$str = 'From: My Name <[email protected]>
To: [email protected]
Message-ID: <[email protected]>';
$old = array("My Name", "To: [email protected]\n");
$new = array("New Name", "");
Upvotes: 1