开发者

how would i get <246.64260, 167.12500, 24.62500> in to separates variables?

if i have <246.64260, 167.12500, 24.62500> each number can be from 1 to 256. I need to get it in to $X as 246, $Y as 167 and $Z as 24

How would i do this? I was thinking to remove开发者_如何学Python all the spaces and them explode to get

X 246.64260

Y 167.12500

Z 24.62500

then explode again to get X 246 Y 167 Z 24

Is this the best way of doing this?


$input  = '<246.64260, 167.12500, 24.62500>';
$output = str_replace(array('<','>',' '), '', $input);
$output = explode(',', $output);
$output = array_map('intval', $output);

list($X, $Y, $Z) = $output;


$string  = '<246.64260, 167.12500, 24.62500>';
$str_esc = str_replace(array('<','>',' '), '', $string );
$output = explode(',', $str_esc);
$output = array_map('intval', $output);
echo "<pre>";
print_r($output);

reference

  1. array_map

  2. intval


I'm going to blow your mind and do it really easily in one line (two if you count the string):

$str = '<246.64260, 167.12500, 24.62500>';
list( $X, $Y, $Z ) = array_map( 'intval', explode( ',', trim( $str, '<>' ) ) );

This will trim off the leading GT and LT characters, then explode the numbers into an array using the commas. Leading whitespace (surprisingly) doesn't matter with intval so it is simply mapped to the separated array and then the results are separated into the $X, $Y, and $Z variables you asked for.


$str = '<246.64260, 167.12500, 24.62500>';
$str = substr(1, strlen(trim($str)) - 1);

$array = explode(',' , $str);
$array = array_map('intval', $array);

list($X, $Y, $Z) = $array;


Probably not the most efficient method, but you could use preg_match_all to put the truncated integer values into a 2D array and move it into X, Y and Z from there.

So something like:

$input = "<246.64260, 167.12500, 24.62500>";
$matches = array();
preg_match_all("([0-9]+)\.[0-9]+", $input, $matches);
$x = $matches[0][0];
$y = $matches[1][0];
$z = $matches[2][0];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜