PHP preg_replace 单行,忽略多行可能吗?
我花了几个小时在这上面,但无法弄清楚,但由于我缺乏 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;
它时,没有删除变量之间的单行,同时忽略了导致注释的双空格。
I have spent a few hours on this and cannot figure it out but due to my lack of preg_match knowledge even after studying it may be something easy. This works in removing multiple lines into one line:
$string = preg_replace('/^\n|^[\t\s]\n/m', "", $string);
How can I reverse its function so that it ignores multiple lines and removes single lines of space? So if the input is:
one
two
three
It would remove the space between one and two, but ignore the multiple spaces before three so the result would look like:
one
two
three
Thanks.
EDIT POST
Thanks guys. 3emad, your code works for my example. I was wrong, I want this to work with code instead of just my text and when I tried using
// ----- 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;
it didn't remove the single line between the variables while ignoring the double space leading to the comments.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是正则表达式:
这适用于您的示例,您可以在以下位置测试它: RegExr
秘密是使用积极的前瞻匹配,您可以此处了解有关“前瞻”的更多信息
有用正则表达式的 PHP 参考
Here is the regular expression:
This works for your example, you can test it at: RegExr
the secret was to use a positive look ahead matching, you can learn more about "look ahead" here
Helpful PHP reference for regular expressions
不确定这对您来说是完美的解决方案,这将删除多余的行+多余的空格+制表符
Not sure this is perfect solution for you, this will remove extra line + extra space + tabs