# PHP Compound Equation Parser

## Recommended Posts

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!

##### Share on other sites

• 3 months later...

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!

##### Share on other sites

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 by Xittenn

## Create an account

Register a new account