Jump to content

PHP Compound Equation Parser

Featured Replies

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!

  • 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!

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

Archived

This topic is now archived and is closed to further replies.

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.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.