【问题标题】:PHP preg_replace single lines, ignore multiple lines possible?PHP preg_replace 单行,忽略多行可能吗?
【发布时间】:2011-10-04 05:53:24
【问题描述】:

我在这上面花了几个小时,但由于我缺乏 preg_match 知识,即使在学习之后也可能很容易。这适用于将多行删除为一行:

$string = preg_replace('/^\n|^[\t\s]\n/m', "", $string); 

如何反转其功能,使其忽略多行并删除单行空格?所以如果输入是:

one

two



three

它将删除一到二之间的空格,但忽略三之前的多个空格,因此结果如下所示:

one
two



three

谢谢。

编辑帖子

谢谢各位。 3emad,您的代码适用于我的示例。我错了,我希望它与代码一起工作,而不仅仅是我的文本,当我尝试使用时

// ----- limits -----



$new_limit = 7;       // maximum days in What's New section

$hot_limit = 20;      // top 20 most accessed links

$toprated_limit = 20; // top 20 most rated links 



// ----- bold the keyword in search result -----



$bold_keyword = 1;

它没有删除变量之间的单行,而忽略了通向 cmets 的双空格。

【问题讨论】:

  • 每一行是否只包含一个单词?
  • 不,它们包含所有类型的数据:数字、符号、空格、制表符和字母
  • 查看答案,希望对您有所帮助。

标签: php preg-replace


【解决方案1】:

这里是正则表达式:

[\r|\r\n](?=\w)

这适用于您的示例,您可以在以下位置进行测试:RegExr

秘诀是使用积极的前瞻匹配,您可以了解更多关于“前瞻”here

$str = '// ----- limits -----



$new_limit = 7;       // maximum days in What\'s New section

$hot_limit = 20;      // top 20 most accessed links

$toprated_limit = 20; // top 20 most rated links 



// ----- bold the keyword in search result -----



$bold_keyword = 1;';

echo '<pre>';
echo preg_replace('/\r?\n(?=[\w|\$])/m','',$str);
echo '</pre>';

对正则表达式很有帮助的PHP reference

【讨论】:

  • 感谢您的宝贵时间,但在使用上述代码时出现 PHP 错误:警告:preg_replace() [function.preg-replace]: Unknown modifier '('
  • 使用这个模式:'/\r?\n(?=\w)/' 我已经添加了一个php代码版本。
  • 感谢 3emad,它适用于我的示例,但我错了。我希望它可以与您在我编辑的帖子中看到的变量一起使用。我希望它删除变量之间的空格,同时在评论部分之前/之后留下多个空格。
  • 请在 pastebin 中添加格式,以便它可以在您的实际文本上运行
  • 一切都好?我想给你写一个更灵活的,不是严格的“$”,我仍然面临着双重问题,仍在分析中
【解决方案2】:

不确定这是否适合您,这将删除多余的行 + 额外的空间 + 制表符

<?php
$input="this is  nimit

and friends
    this must be in single line.

@234 234234
                I have test this.
";
$input = str_replace(' ','_',$input);
$result = preg_replace('/\s+/','<br>',$input);
$result = str_replace('_',' ',$result);
echo $result;
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 2011-05-20
    相关资源
    最近更新 更多