使用PHP从字符串中获取数字 [英] Get numbers from string with PHP

查看:55
本文介绍了使用PHP从字符串中获取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字符串:

$one = 'foo bar 4 baz (5 qux quux)';
$two = 'bar baz 2 bar';
$three =  'qux bar 12 quux (3 foo)';
$four = 'foo baz 3 bar (13 quux foo)';

如何找到这些字符串中的数字?

How can I find the numeric digits in these strings?

也许具有功能:

function numbers($string){

    // ???

    $first = ?;
    $second = ?;
}

例如:

function numbers($one){

    // ???

    $first = 4;
    $second = 5;
}

function numbers($two){

    // ???

    $first = 2;
    $second = NULL;
}

最好的方法可能是正则表达式,但是如何在我的示例中使用它呢?也许没有正则表达式?

Best way for this maybe is regex, but how can I use this for my example? Maybe without regex?

推荐答案

您可以为此使用正则表达式. \d 转义序列将匹配主题字符串中的所有数字.

You can use regular expressions for this. The \d escape sequence will match all digits in the subject string.

例如:

<?php

function get_numerics ($str) {
    preg_match_all('/\d+/', $str, $matches);
    return $matches[0];
}

$one = 'foo bar 4 baz (5 qux quux)';
$two = 'bar baz 2 bar';
$three = 'qux bar 12 quux (3 foo)';
$four = 'foo baz 3 bar (13 quux foo)';

print_r(get_numerics($one));
print_r(get_numerics($two));
print_r(get_numerics($three));
print_r(get_numerics($four));

https://3v4l.org/DiDBL

这篇关于使用PHP从字符串中获取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆