PHP Replace With New Line

2019-09-19 19:53发布

问题:

On a html page I have this.

</h2>
<ol>

The page is contained in a variable called $content. I want to replace this with something else but the code doesn't work.

$content = str_replace("</h2><ol>", $title, $content);

What should i put there instead of .

回答1:

Rather use preg_replace for this:

preg_replace("/<\/h2>[\s]*<ol>/", $title, $content);

Regardless of how you do it, it doesn't really make sense. An <h2> is started, but you remove that closing tag and the starting tag for the <ol>, which will also have a closing tag I assume? Seems like your output is going to be wrong regardless.



回答2:

\n is the new line character:

$content = str_replace("</h2>\n<ol>", $title, $content);

Just make sure you always use it in double quotes for PHP to recognize it as an escape sequence otherwise it will interpret it as a literal "slash" "n".



回答3:

Depending on your IDE / text editor, or how you're accessing your file (ie: ssh/ftp/etc.) You may also consider using or playing around with one of the following escape characters for newline

"</h2>\r\n<ol>" or "</h2>\n<ol>" or even "</h2>\r<ol>"


标签: php wordpress