gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 22:53:10 24 4
gpt4 key购买 nike

我有字符串:

$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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com