简体   繁体   中英

php replace regular expression

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.

$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 )

$str = "Will you please slow down?You're gonna kill someone.Seriously!";
echo preg_replace('/(!|\?|\.)([^\s\.\?!])/', '\1 \2', $str);
$str = "This is a sentence.This is the next one.";
echo preg_replace("#\.(\S)#", '. \1', $str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM