从PHP中的字符串中提取单个值

时间:2015-08-27 19:03:31

标签: php extraction

我有一个这样的字符串:

$string = 'rgb(178, 114, 113)';

我希望提取该

的各个值
$red = 178;
$green = 114;
$blue = 113;

3 个答案:

答案 0 :(得分:4)

您可以使用regular expression

preg_match_all('(\d+)', $string, $matches);
print_r($matches);

输出:

Array
(
    [0] => Array
        (
            [0] => 178
            [1] => 114
            [2] => 113
        )
)

希望这有帮助。

答案 1 :(得分:1)

如果您的字符串始终以rgb(开头并以)结尾,那么您可以truncate the string只使用178, 114, 113

$rgb = substr($string, 4, -1); //4 is the starting index, -1 means second to last character

然后到convert the list to an array

$vals = explode(', ', $rgb);
//or you could use just ',' and trim later if your string might be in the format `123,123, 123` (i.e. unknown where spaces would be)

此时,$vals[0]为红色,$vals[1]为绿色,$vals[2]为蓝色。

答案 2 :(得分:0)

使用preg_match_all和list,您可以获得所需的变量:

$string = "rgb(178, 114, 113)";
$matches = array();
preg_match_all('/[0-9]+/', $string, $matches);
list($red,$green,$blue) = $matches[0];

请注意,这并不验证原始字符串确实有三个整数值。