Solved

PHP/REGEX: Remove last unfinished sentence were period ends sentence

Posted on 2014-02-19
2
431 Views
Last Modified: 2014-02-19
Using PHP and REGEX, how can I remove the last incomplete sentence?   For example,
Hello, world.  Joe D. is a
Should become:
Hello, world.

This code works if there are no initials followed by periods:
$mystring = preg_replace("/[\w\s',]*$/",'',$mystring);

Open in new window

http://www.experts-exchange.com/Programming/Languages/Regular_Expressions/Q_28369053.html

Any period that follows one single letter does not end a sentence.

Thanks!
0
Comment
Question by:hankknight
2 Comments
 
LVL 35

Accepted Solution

by:
Terry Woods earned 500 total points
ID: 39871629
This will work for the example provided:
$mystring = preg_replace("/([^!.?]|[A-Z]\.)*$/",'',$mystring);

Open in new window


However, when the initial is an upper case letter i then there is a very small chance (depending on your data) that it's not actually an initial and it's part of the sentence instead, as "I" is a word.
0
 
LVL 34

Expert Comment

by:Dan Craciun
ID: 39871662
$mystring = preg_replace("/[\w\s\',]*(( \w\.)*[\w\s\',]*)*$/",'',$mystring);

Open in new window


This works for all the following cases:
Hello, world.  Joe D. is a
Hello, world.  Joe is a
Hello, World. Joe
Hello, world. Joe B. joe d.
Hello, world. b. jor d.

HTH,
Dan
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question