如何用正则表达式替换新行 [英] How to replace new lines by regular expressions

查看:35
本文介绍了如何用正则表达式替换新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用正则表达式设置任意数量的新行?

How can I set any quantity of new lines with a regular expression?

$var = "<p>some text</p><p>another text</p><p>more text</p>";
$search = array("</p>\s<p>");
$replace = array("</p><p>");
$var = str_replace($search, $replace, $var);

我需要删除两个段落之间的每个新行 (\n),而不是
.

I need to remove every new line (\n), not <br/>, between two paragraphs.

推荐答案

首先,str_replace()(您在原始问题中引用了它)用于查找文字字符串并替换它.preg_replace() 用于查找与正则表达式匹配的内容并替换它.

To begin with, str_replace() (which you referenced in your original question) is used to find a literal string and replace it. preg_replace() is used to find something that matches a regular expression and replace it.

在下面的代码示例中,我使用 \s+ 来查找一个或多个空格(换行、制表符、空格...).\s 是空格+ 修饰符表示前面的一个或多个.

In the following code sample I use \s+ to find one or more occurrences of white space (new line, tab, space...). \s is whitespace, and the + modifier means one or more of the previous thing.

<?php
  // Test string with white space and line breaks between paragraphs
$var = "<p>some text</p>    <p>another text</p>
<p>more text</p>";

  // Regex - Use ! as end holders, so that you don't have to escape the
  // forward slash in '</p>'. This regex looks for an end P then one or more (+)
  // whitespaces, then a begin P. i refers to case insensitive search.
$search = '!</p>\s+<p>!i';

  // We replace the matched regex with an end P followed by a begin P w no
  // whitespace in between.
$replace = '</p><p>';

  // echo to test or use '=' to store the results in a variable. 
  // preg_replace returns a string in this case.
echo preg_replace($search, $replace, $var);
?>

现场示例

这篇关于如何用正则表达式替换新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆