php - 使用 PHP 从字符串中获取数字

标签 php regex

我有字符串:

$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)';

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

也许有功能:

function numbers($string){

    // ???

    $first = ?;
    $second = ?;
}

例如:

function numbers($one){

    // ???

    $first = 4;
    $second = 5;
}

function numbers($two){

    // ???

    $first = 2;
    $second = NULL;
}

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

最佳答案

您可以使用 regular expressions为了这。 \d escape sequence将匹配主题字符串中的所有数字。

例如:

<?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 - 使用 PHP 从字符串中获取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11243447/

相关文章:

php - 随机化 SQL 结果

php - 我如何获得第一个单词正则表达式

regex - perl 或 matlab 正则表达式中的滑动窗口模式匹配

php - MySQL : show 0 and transaction type when no result found

php - 如何将此 xml feed 导入到 sql 中并自动更新?

php - 使用 Javascript 获取下拉列表的选定名称

java - 用于在 JSON 值中有选择地转义字符的正则表达式

c# - 用于检测字符串中重复的正则表达式

Python 3 : How can I get os. getcwd() 与 re.sub() 配合得很好吗?

python - 简单的正则表达式问题