Anni
Anni

Reputation: 85

How to get specific part of a strings from a string using php?

I have a RGBA color in this format:

RGBA:1.000000,0.003922,0.003922,0.003922

How can I separate each value from this string such as:

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

I want to do this in php.

Upvotes: 0

Views: 68

Answers (3)

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44844

Another way using regex is

$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

Upvotes: 0

kidz
kidz

Reputation: 308

Code snippet should be like this:

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

Upvotes: 0

Amal Murali
Amal Murali

Reputation: 76646

Split the string into two parts with : as the delimiter, take the second part, and split the result again with , as the delimiter. Assign the values to variables. All this could be done in one line, as follows:

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

Output:

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

Demo

Upvotes: 2

Related Questions