解析包含两个数字的字符串并将它们分配给两个变量
$pos
在一个字符串中包含两个由空格分隔的数字。
$pos = 98.9 100.2
我怎样才能把它分成2个变量?我显然必须检查两者之间的空间。
之后我想有两个变量:
$number1 = 98.9
$number2 = 100.2
$pos
contains two numbers delimited by a space in one string.
$pos = 98.9 100.2
How can I split this into 2 variables? I obviously have to check for the space in between.
I would like to have two variables afterwards:
$number1 = 98.9
$number2 = 100.2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
但是,在执行此操作之前,请确保字符串具有正确的格式。
However, make sure the string has the right format before doing this.
如果它始终是一个空格,则检查
And in your case you have
它给你一个数组:
Use +0 to force the cast :)
If it is always a space, then check
And in your case you have
which gives you an array:
Use +0 to force the cast :)
你可以使用:
You could use:
使用
sscanf()
而不是explode()
或preg_split()
等通用字符串拆分函数,您可以立即对隔离的字符串进行数据类型化价值观。对于示例字符串,使用
%f
两次将提取空格分隔的值并将两个数值转换为浮点数/双精度数。代码:(Demo)
输出:
有一种替代语法,其行为方式相同,但返回值如下一个数组。 (演示)
输出:
Using
sscanf()
instead of general-use string splitting functions likeexplode()
orpreg_split()
, you can instantly data-type the isolated values.For the sample string, using
%f
twice will extract the space-delimited values and cast the two numeric values as floats/doubles.Code: (Demo)
Output:
There is an alternative syntax which will act the same way, but return the values as an array. (Demo)
Output: