I would like to extract a number (4 positions) from a string which is stored in a database.
e.g. "Mountain guesthouse (2340m) in Radons" How is this to be done? It is possible that the number is like 2.340m
<?php
//$string = 'Mountain guesthouse (2340m) in Radons';
//preg_match('#([0-9]+)m#is', $string, $matches);
//$peak = number_format($matches[1], 0, ',', '.');
//EDIT
$string = 'Mountain guesthouse (23.40m) in Radons';
$preg_match('#([0-9\.]+)m#is', $string, $matches);
$peak=$matches[1];
echo $peak . 'm'; # 23.40m
?>
Live: http://ideone.com/42RT4
Edit live: https://ideone.com/hNJxG
Your question is a little vague. Is m always a part of the number? Do you want to extract it too? Does the number always consist of 4 digits? The below matches any integer or floating point integer without scientific notation.
if (preg_match('/[0-9]*\.?[0-9]+/', $subject, $regs)) {
$result = $regs[0];
#check if . is present and if yes length must be 5 else length must be 4
if (preg_match('/\./', $result) && strlen($result) == 5) {
#ok found match with . and 4 digits
}
elseif(strlen($result) == 4){
#ok found 4 digits without .
}
}
preg_match('/\d\.?\d{3}/', $text, $matches);
Matches a number followed by an optional dot and 3 more numbers.
php > $text = "Mountain guesthouse (2340m) in Radons";
php > preg_match('/\d\.?\d{3}/', $text, $matches);
php > print_r($matches);
Array
(
[0] => 2340
)
(Edited from @webarto's answer)
<?php
$string = 'Mountain guesthouse (23.40m) in Radons';
preg_match('#([0-9\.]+)m#is', $string, $matches);
$peak = $matches[1];
echo $peak . 'm'; # 2.340m
?>