phpreplacenewlinemultiline

Failing to use str_replace() with \n\r while matching multi-line text


How to use str_replace() to append a string?

Input:

</div> 
</li> 
</ul>

Desired output:

</div> 
</li> 
</ul>
aaa

All the tags in a new line.

I tried

$str = str_replace('</div>\n\r</li>\n\r</ul>', '</div>\n\r</li>\n\r</ul>\n\raaa', $str);  

Updated coding attempt (still failing):

$str = <<<EOT
</div>
</li>
</ul>
EOT;

$str = str_replace("</div>\n\r</li>\n\r</ul>", "</div>\n\r</li>\n\r</ul>\n\raaa", $str);  

echo $str;

Solution

  • \n in single quotes is a literal \ and a literal n, rather than a \n, to get the line breaks you need to use double quotes:

    $str = str_replace("</div>\r\n</li>\r\n</ul>", "</div>\r\n</li>\r\n</ul>\r\naaa", $str);  
    

    Also, you should be replacing \r\n not \n\r as Windows line breaks are a carriage return \r followed by a line break \n.