Jump to content

PHP Compound Equation Parser


RyanJ

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!

Link to comment
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!

Link to comment
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
Link to comment
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.