Reputation: 123
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 preceding 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 ".".
Upvotes: 0
Views: 1053
Reputation: 352
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>");
?>
Upvotes: 0
Reputation: 39197
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.
Upvotes: 2
Reputation: 526763
$input = "This is another text string. 2.0 times longer.";
echo preg_replace("/(^\.|\s\.|\.\s|\.$)/", " $1", $input);
Upvotes: 0