如何使用PHP从字符串中获取字符串的特定部分?

时间:2014-04-10 19:00:09

标签: php

我有这种格式的RGBA颜色:

RGBA:1.000000,0.003922,0.003922,0.003922

如何将每个值与此字符串分开,例如:

var alpha = 1.000000;
var red = 0.003922;
var green = 0.003922;
var blue = 0.003922;

我想在php中这样做。

3 个答案:

答案 0 :(得分:2)

将字符串拆分为两部分,:作为分隔符,取第二部分,然后再次使用,作为分隔符拆分结果。将值分配给变量。所有这些都可以在一行中完成,如下所示:

list($alpha, $red, $green, $blue) = explode(',', explode(':', $str, 2)[1]);

输出:

string(8) "1.000000"
string(8) "0.003922"
string(8) "0.003922"
string(8) "0.003922

Demo

答案 1 :(得分:0)

代码段应该是这样的:

$rgba = "1.000000,0.003922,0.003922,0.003922";
$rgba = explode(',', $rgba);
list($red, $green, $blue, $alpha) = $rgba;

答案 2 :(得分:0)

使用正则表达式的另一种方法是

$str = 'RGBA:1.000000,0.003922,0.003922,0.003922';
preg_match_all("/(\d+\.+\d+)/", $str, $output_array);

list($alpha, $red, $green, $blue) = $output_array[1] ;

https://eval.in/135090