RyanJ Posted November 29, 2010 Posted November 29, 2010 Hi all, Does anyone know of a PHP compound parser that takes a compounds formula as input (e.g. UO2(CO3)) and then spits out an array of the element symbols with the number of each present in the specified formula, in this case U=1, O=5,C=1. Any help appreciated!
aliu Posted March 12, 2011 Posted March 12, 2011 Try this: <?php $input = 'UO2(CO3)'; $find = array('(', ')'); $input_clean = str_replace($find, "", $input); // replace '(' and ')' with nothing $letters = str_split($input_clean); $letter_counter = array(); $last_char = null; foreach ($letters as $char) { if (preg_match("/\d+/", $char)) { $letter_counter["$last_char"] = $letter_counter["$last_char"] + $char - 1; } else { $letter_counter["$char"]++; } $last_char = $char; } var_dump($letter_counter); ?> Quickly whipped it up but it works =) Allen Try this: <?php $input = 'UO2(CO3)'; $find = array('(', ')'); $input_clean = str_replace($find, "", $input); // replace '(' and ')' with nothing $letters = str_split($input_clean); $letter_counter = array(); $last_char = null; foreach ($letters as $char) { if (preg_match("/\d+/", $char)) { $letter_counter["$last_char"] = $letter_counter["$last_char"] + $char - 1; } else { $letter_counter["$char"]++; } $last_char = $char; } var_dump($letter_counter); ?> Quickly whipped it up but it works =) Allen Wow...just realized that I was a couple of months too late. Darn!
Xittenn Posted March 12, 2011 Posted March 12, 2011 (edited) Would that have accounted for elements like Li where it is denoted by two letters. Not that this would be any more difficult to add, in that one would simply have to note the locations of letters that are not capitals. Or search based on a library of known elements! Edited March 12, 2011 by Xittenn
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now