preyz
preyz

Reputation: 3169

Regex to insert dot (.) after characters, before new line

I'm reformatting some text, and sometimes I have a string, where there is a sentence which is not ended by a dot.

I'm running various checks for this purpose, and one more I'd like is to "Add dot after last character before new line".

I'm not sure how to form the regular expression for this:]

$string = preg_replace("/???/", ".\n", $string);

Upvotes: 1

Views: 3182

Answers (5)

onin
onin

Reputation: 5760

This works for me:

$content = preg_replace("/(\w+)(\n)/", "$1.$2", $content);

It will match a word immediately followed by a new line, and add a dot in between.

Will match: Hello\n

Will not match: Hello \n or Hello.\n

Upvotes: 0

preyz
preyz

Reputation: 3169

Thanks for all the answers, but none of them really caught all scenarios right.

I fumbled my way to a good solution using the word boundary regex character class:

// Add dot after every word boundary that is followed by a new line.
$string = preg_replace("/[\b][\n]/", ".\n", $string);

I guess [\b][\n] could just as well be \b\n without square brackets.

Upvotes: 0

Toto
Toto

Reputation: 91488

I'd do:

$string = "Add dot after last character before new line\n";
$string = preg_replace("/([^.\r\n])$/s", "$1.", $string);

Upvotes: 1

aelor
aelor

Reputation: 11116

like this I suppose:

<?php
$string = "Add dot after last character before new line\n";
$string = preg_replace("/(.)$/", "$1.\n", $string);
print $string;
?>

This way the dot will be added after the word line in the sentence and before the \n.

demo : http://ideone.com/J4g7tH

Upvotes: 1

Sabuj Hassan
Sabuj Hassan

Reputation: 39385

Try this one:

$string = preg_replace("/(?<![.])(?=[\n\r]|$)/", ".", $string);

negative lookbehind (?<![.]) is checking previous character is not .

positive lookahead (?=[\n\r]|$) is checking next character is a newline or end of string.

Upvotes: 4

Related Questions