Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 21986

Removing three dots after or before a newline

I use this function to remove three dots before or after a newline:

private function trimThreeDots(string $text): string {
    $threeDotsAtTheBeginning = '((^|[\n]{1})[\\.]{3})';
    $threeDotsAtTheEnd = '([\\.]{3}[\n]{1})';

    $pattern = '/' . $threeDotsAtTheBeginning . '|' . $threeDotsAtTheEnd . '/';

    return preg_replace_callback($pattern, function ($str) {
        return str_replace("...", "", $str[0]);
    }, $text);
}

It works, except that in case that I have a string like this one:

"Bla bla bla...
...bla bla bla"

I only get a single match. But I want to get two matches, because I need to remove both occurrences of three dots. I wonder if maybe there is a more straightforward and efficient way to write this regex and getting two matches in the above case?

Upvotes: 3

Views: 391

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

You may use

$s = "Bla bla bla...
...bla bla bla";
echo preg_replace('~(?:\.{3})?(\R)(?:\.{3})?~', '$1', $s);

See the PHP demo and a regex demo.

Details

  • (?:\.{3})? - an optional sequence of 3 dots
  • (\R) - Group 1: any line break sequence
  • (?:\.{3})? - an optional sequence of 3 dots

The $1 replacement replaces the match with the exact line break sequence the regex matches.

Upvotes: 5

Zenoo
Zenoo

Reputation: 12880

You can use the RegEx \.{3}(?=\n)|(?<=\n)\.{3}

  • \.{3}(?=\n) matches the case where the newline is after the dots

  • (?<=\n)\.{3} matches the case where the newline is before the dots

Demo.


PHP:

preg_replace('~\.{3}(?=\n)|(?<=\n)\.{3}~', '', $s);

Upvotes: 2

springbo
springbo

Reputation: 1096

Seems overly complex maybe? What about this?

$re = '/(^\.{3}|\.{3}$)/gm';
$str = 'Bla bla bla...
...bla bla bla';
$subst = '';

$result = preg_replace($re, $subst, $str);

echo "The result of the substitution is ".$result;

Upvotes: 0

Related Questions