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

Extract individual values from a string in PHP

我有这样的字符串:

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

我想提取其中的各个值

$red = 178;
$green = 114;
$blue = 113;

如果您的字符串始终以 rgb( 开头并以 ) 结尾,那么您可以 truncate the string178, 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]为蓝色。

您可以使用 regular expression

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

输出:

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

希望对您有所帮助。

使用preg_match_all和list,可以得到你想要的变量:

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

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