Search code examples
phpstr-replaceline-breaks

Ignore break line with str_replace


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 <myemail@myname.com>
        To: storm@yahoo.com
        Message-ID: <1638618225.203837.1426581391642.JavaMail.yahoo@mail.yahoo.com>';

$old = array("My Name", "To: storm@yahoo.com");
$new   = array("New Name", "");
echo str_replace($old, $new, $str );

Output:

From: New Name 

Message-ID: <1638618225.203837.1426581391642.JavaMail.yahoo@mail.yahoo.com>

Unfortunately after removing To: storm@yahoo.com, the code will create a line break. How can I use str_replace without creating new break line?


Solution

  • 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 <myemail@myname.com>
            To: storm@yahoo.com
            Message-ID: <1638618225.203837.1426581391642.JavaMail.yahoo@mail.yahoo.com>';
    
    $old = array("My Name", "To: storm@yahoo.com\n");
    $new = array("New Name", "");