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

编程入门 行业动态 更新时间:2024-10-28 04:16:22
本文介绍了使用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));

3v4l/DiDBL

更多推荐

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

本文发布于:2023-11-06 04:34:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562725.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   数字   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!