REGEX - php preg_replace:

How to replace part of a string based on a "." (period) character only if it appears after/before/between a word(s), not when it is before/between any number(s).

Example:

This is a text string.  

-Should be able to replace the "string." with "string ." (note the Space between the end of the word and the period)

Example 2

This is another text string. 2.0 times longer.  

-Should be able to replace "string." with "string ." (note the Space between the end of the word and the period) -Should Not replace "2.0" with "2 . 0"

It should only do the replacement if the "." appears at the end/start of a word.

Yes - I've tried various bits of regex. But everything I do results in either nothing happening, or the numbers are fine, but I take the last letter from the word preceeding the "." (thus instead of "string." I end up with "strin g.")

Yes - I've looked through numerous posts here - I have seen Nothing that deals with the desire, nor the "strange" problem of grabbing the char before the ".".

$input = "This is another text string. 2.0 times longer.";
echo preg_replace("/(^\.|\s\.|\.\s|\.$)/", " $1", $input);

http://ideone.com/xJQzQ

You can use a lookbehind (?<=REXP)

preg_replace("/(?<=[a-z])\./i", "XXX", "2.0 test. abc")    // <- "2.0 testXXX abc"

which will only match if the text before matches the corresponding regex (in this case [a-z]). You may use a lookahead (?=REXP) in the same way to test text after the match.

Note: There is also a negative lookbehind (?<!REXP) and a negative lookahead (?!REXP) available which will reject matches if the REXP does not match before or after.

I'm not too good with the regex, but this is what I would do to accomplish the task with basic PHP. Basically explode the entire string by it's . values, look at each variable to see if the last character is a letter or number and add a space if it's a number, then puts the variable back together.

<?
$string = "This is another text string. 2.0 times longer.";
print("$string<br>");
$string = explode(".",$string);
$stringcount = count($string);
for($i=0;$i<$stringcount;$i++){
    if(is_numeric(substr($string[$i],-1))){
        $string[$i] = $string[$i] . " ";
    }
}
$newstring = implode('.',$string);
print("$newstring<br>");
?>

It should only do the replacement if the "." appears at the end/start of a word.

search: /([a-z](?=\.)|\.(?=[a-z]))/
replace: "$1 "
modifiers: ig (case insensitive, globally)

Test in Perl:

use strict;
use warnings;

my $samp = '
This is another text string. 2.0 times longer.
I may get a string of "this and that.that and this.this 2.34 then that 78.01."
';

$samp =~ s/([a-z](?=\.)|\.(?=[a-z]))/$1 /ig;

print "$samp";

Input:
This is another text string. 2.0 times longer.
I may get a string of "this and that.that and this.this 2.34 then that 78.01."

Output:
This is another text string . 2.0 times longer .
I may get a string of "this and that . that and this . this 2.34 then that 78.01."