将字符串分解为变量 [英] explode string into variables

查看:91
本文介绍了将字符串分解为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将字符串分解为变量,例如

Is there a way to explode a string into variables e.g

some_function($min, $max, "3, 20");

为$ min分配值3,为$ max分配值20.

such that $min is assigned the value 3 and $max is assigned the value 20.

我知道我可以简单地使用

I know I can simply use

$data = explode("3, 20");

只是想知道是否还有另一种方法.

just wondering if there is another way.

推荐答案

PHP的语言构造 list() 可以通过分配数组来对变量(甚至其他数组键)执行多个分配.

PHP's language construct list() can perform multiple assignments to variables (or even other array keys) by assigning an array.

list($min, $max) = explode(",", "3,20");

但是,您仍然需要对变量应用trim(),因为$max值将有一个前导空格,或者将explode()替换为preg_split('/\s*,\s*/', $string)以在逗号和周围的空白处将其分割.

However, you would still need to apply a trim() to your variables since the $max value would have a leading space, or replace explode() with preg_split('/\s*,\s*/', $string) to split it on commas and surrounding whitespace.

注意:对list()谨慎使用,以确保要分配的数组包含与list()具有变量的元素相同数量的元素.在PHP 5.x中,它们是从右到左分配的,而不是从左到右分配的,因此,如果您碰巧用左侧的原始内容覆盖左侧的变量,则可能会得到意想不到的结果.这将在PHP文档中使用示例 进行详细说明.

Note: Use caution with list() to be sure that the array you're assigning contains the same number of elements as list() has variables. They are assigned from right to left in PHP 5.x, not left to right, so if you happen to overwrite a variable on the left with its original contents on the right, you may get unexpected results. This is detailed with examples in the PHP docs.

针对PHP 7的更新:PHP 7更改了分配顺序行为,以使list()参数从左到右分配

Update for PHP 7: PHP 7 changes the assignment order behavior such that list() arguments are assigned from left to right

这篇关于将字符串分解为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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