Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
974 views
in Technique[技术] by (71.8m points)

regex - Extract floating point numbers from a string in PHP

I would like to convert a string into floating numbers. For example

152.15 x 12.34 x 11mm

into

152.15, 12.34 and 11

and store in an array such that $dim[0]=152.15, $dim[1]=12.34, $dim[2]=11.

I would also need to handle things like

152.15x12.34x11 mm

152.15mmx12.34mm x 11mm

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$str = '152.15 x 12.34 x 11mm';
preg_match_all('!d+(?:.d+)?!', $str, $matches);
$floats = array_map('floatval', $matches[0]);
print_r($floats);

The (?:...) regular expression construction is what's called a non-capturing group. What that means is that chunk isn't separately returned in part of the $mathces array. This isn't strictly necessary in this case but is a useful construction to know.

Note: calling floatval() on the elements isn't strictly necessary either as PHP will generally juggle the types correctly if you try and use them in an arithmetic operation or similar. It doesn't hurt though, particularly for only being a one liner.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...