我花了几个小时在这上面,但无法弄清楚,但由于我缺乏 preg_match 知识,即使在学习之后,它也可能很容易。这适用于将多行删除为一行:
$string = preg_replace('/^\n|^[\t\s]\n/m', "", $string);
如何反转它的功能,以便它忽略多行并删除单行空格?因此,如果输入是:
one
two
three
它将删除 1 和 2 之间的空格,但忽略 3 之前的多个空格,因此结果如下所示:
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;
它没有删除变量之间的单行,同时忽略导致注释的双空格。
最佳答案
这是正则表达式:
[\r|\r\n](?=\w)
这适用于您的示例,您可以在以下位置进行测试:RegExr
secret 是使用正向前瞻匹配,您可以了解更多有关“前瞻”的信息 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 单行,忽略多行可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7643795/