从字符串中删除双空格和换行符后的空格

5

所以,首先我有这个输入

$string = "Lorem ipsum 
dolor sit amet, consectetur adipiscing 
elit https://www.youtube.com/watch?v=example sed do eiusmod tempor incididunt https://www.youtube.com/watch?v=example2 https://www.youtube.com/watch?v=example3";

然后我想使用正则表达式从$string中删除URL。

$string = preg_replace('/[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)/', '', $string);

我将字符串中所有的URL删除后,输出结果为:

Lorem ipsum 
dolor sit amet, consectetur adipiscing 
 elit  sed do eiusmod tempor incididunt  

问题在于,有两个空格,我想让它看起来更整洁。

我尝试使用以下方法,将所有的双倍空格替换为单个空格:

$string = preg_replace('/\x20+/', ' ', $string);

另一个问题出现了,就是换行符后面有一个空格。

Lorem ipsum 
dolor sit amet, consectetur adipiscing 
 elit sed do eiusmod tempor incididunt

这让我感到不舒服。

我需要一个解决方案来去掉URL,但同时使其整洁。 我想要的最终结果是这样的:

Lorem ipsum 
dolor sit amet, consectetur adipiscing
elit sed do eiusmod tempor incididunt

抱歉看起来有点奇怪,谢谢。
2个回答

2
使用preg_replace()来删除所有URL。
使用trim()来删除任何剩余的空格。
再次使用preg_replace()来删除任何双倍空格。(正则表达式
然后,将行首的任何空格替换为无以删除它们。
<?php

    $r = '/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i';
    $string = "Lorem ipsum
    dolor sit amet, consectetur adipiscing
    elit https://www.youtube.com/watch?v=example sed do eiusmod tempor incididunt https://www.youtube.com/watch?v=example2 https://www.youtube.com/watch?v=example3";

    // Remove url's
    $clean = preg_replace($r, ' ', $string);

    // Trim whitespaces
    $clean = trim($clean);

    // Replace dubble-space with single space
    $clean = preg_replace( '/\h+/', ' ', $clean);

    // Remove any spaces after newline
    $clean = preg_replace('/^ /m', '', $clean);

    // Show result
    echo $clean;

输出:

Lorem ipsum 
dolor sit amet, consectetur adipiscing 
elit sed do eiusmod tempor incididunt

在线试用


注意:这段代码可以通过合并一些调用来简化,但我选择不这样做以便更清晰地显示步骤。


1

我会使用这些正则表达式:

$string = "Lorem ipsum 
dolor sit amet, consectetur adipiscing 
elit https://www.youtube.com/watch?v=example sed do eiusmod tempor incididunt https://www.youtube.com/watch?v=example2 https://www.youtube.com/watch?v=example3";

$string = preg_replace('/[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)([ ]*)?/', '', $string);
$string = preg_replace('/(([ ]*)?(\r\n|\n)([ ]*)?)/', "\r\n", $string); # Remove any potantial space before line break and remove any potential space after line break

echo $string;

输出

Lorem ipsum
dolor sit amet, consectetur adipiscing
elit sed do eiusmod tempor incididunt 

注意:我刚刚在匹配URL的正则表达式中添加了([ ]*)?,以确保还可以匹配URL后面的空格。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接