Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php replace regular expression

Tags:

regex

replace

php

I need to use php to add a space between a period and the next word/letter when there's none.

For example, "This is a sentence.This is the next one." needs to become "This is a sentence. This is the next one." Notice the added space after the first period.

My problem is that even if I'm able to make a regular expression that finds every dot followed by a letter, how do I then replace that dot with a "dot + space" and keep the letter?

Also it needs to keep the case of the letter, lower or upper.

Thanks for your input.

like image 499
Enkay Avatar asked Dec 28 '22 16:12

Enkay


1 Answers

$regex = '#\.(\w)#';
$string = preg_replace($regex, '. \1', $string);

If you want to capture more than just periods, you can do:

preg_replace('#(\.|,|\?|!)(\w)#', '\1 \2', $string);

Simply add the characters you want replaced into the first () block. Don't forget to escape special characters (http://us.php.net/manual/en/regexp.reference.meta.php)

like image 62
ircmaxell Avatar answered Jan 08 '23 18:01

ircmaxell