Telling apart full stop & decimal point
Posted: Sun Nov 28, 2010 7:18 am
How can I check if a dot is in between two numbers in a string?
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
Code: Select all
$instances = preg_match_all('/[^0-9]\./', $string, $matches);
$sentences = array();
for ($i = 0; $i < $instances; $i++)
{
$sentences[$i] = substr($string, 0, stripos($string, $matches[0][$i]) + 2);
$string = substr($string, strlen($sentences[$i]));
}
foreach ($sentences as $sentence)
{
echo $sentence . "<br />";
}Code: Select all
$input = preg_replace("/[0-9]\.[0-9]/", ",", $input);What is the aim of that?lenton wrote:I can't seem to get it working. I could change the decimal into a comer then change it back once the sentences have been split.
Code: Select all
$str = "My current ranking is 408. Pi is close to 3.14.
I have 13.25 chickens. Yikes! Where did the .25 come from?
Did you know 123.nobody@nowhere.not is not a real email address?
My IP address is 127.0.0.1. I bet yours is too.";
print_r(preg_split('/(?<=[.!?])\s+/', $str));
/*
Array
(
[0] => My current ranking is 408.
[1] => Pi is close to 3.14.
[2] => I have 13.25 chickens.
[3] => Yikes!
[4] => Where did the .25 come from?
[5] => Did you know 123.nobody@nowhere.not is not a real email address?
[6] => My IP address is 127.0.0.1.
[7] => I bet yours is too.
)
*/Two solutions... but don't say I didn't warn you.*lenton wrote:code that replaces '.' with a ',' where matches /[0-9]\.[0-9]/
Code: Select all
$subject = 'I have 4.5 ideas. There are 5,280* feet
in 1 mile.6 is a typo. Pi is near 3.14.';
// Lookbehind and lookahead assertions:
var_dump(preg_replace('/(?<=\d)\.(?=\d)/', ',', $subject));
/*
string(78) "I have 4,5 ideas. There are 5,280* feet
in 1 mile.6 is a typo. Pi is near 3,14."
*/
// Back references to captured subpatterns:
var_dump(preg_replace('/(\d)\.(\d)/', '\1,\2', $subject));
/*
string(78) "I have 4,5 ideas. There are 5,280* feet
in 1 mile.6 is a typo. Pi is near 3,14."
*/