首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从字符串中提取数字(4个位置)

从字符串中提取数字(4个位置)
EN

Stack Overflow用户
提问于 2011-10-16 21:09:25
回答 4查看 177关注 0票数 0

我想从存储在数据库中的字符串中提取一个数字(4个位置)。

例如:“山宾馆(2340米)在拉冬”如何做到这一点?这个数字有可能是2340M

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-10-16 21:18:43

代码语言:javascript
复制
<?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

?>

直播:http://ideone.com/42RT4

编辑实况:https://ideone.com/hNJxG

票数 4
EN

Stack Overflow用户

发布于 2011-10-16 21:13:20

代码语言:javascript
复制
preg_match('/\d\.?\d{3}/', $text, $matches);

匹配后跟可选点的数字和另外3个数字。

代码语言:javascript
复制
php > $text = "Mountain guesthouse (2340m) in Radons";
php > preg_match('/\d\.?\d{3}/', $text, $matches);
php > print_r($matches);
Array
(
    [0] => 2340
)
票数 2
EN

Stack Overflow用户

发布于 2011-10-16 21:11:45

你的问题有点含糊。M总是数字的一部分吗?你想把它也提取出来吗?数字总是由4位数字组成吗?下面匹配不带科学记数的任何整数或浮点整数。

代码语言:javascript
复制
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 .
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7784480

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档