0

I have this string: CO2 + H2O + XO

And I am going for this: CO2 + H2O + NaO.

I have researched this quite a bit and I am at a loss on what to do with a mixture of strings and arrays.

$reactant = 'CO2 + H2O + XO';

$products = str_split($reactant);

foreach ($products as $splitresult)
{
  $splitresult = str_replace('X', 'Na', $splitresult); 
}

echo $splitresult;
5
  • do you want to replace all the X's as 'Na' or only when they are next to 'O' ? I ask because as you are working with elements there are other(s) elements including an X as far as I remember, and if you are putting this as just an example and it's not the real scenario specify as much as possible so we can work out something accurate. Commented Dec 16, 2013 at 9:09
  • Ok, so when you say X in string you mean $someElement. This is handled very easily with str_replace($searchFor, $replaceWith, $subject) Commented Dec 16, 2013 at 9:09
  • I am working on decomposition reactions. On this specific one, i don't know the metals and i use place holders i.e X. It only covers upto AP level, so i don't expect anyone looking for X or Y elements. Str_split also seems to work better than explode. Commented Dec 16, 2013 at 9:19
  • @Edwinner can I ask why str_split works better than explode for you? Commented Dec 16, 2013 at 9:36
  • @Stanyer that was before i tried yours. explode does work. Commented Dec 16, 2013 at 9:39

4 Answers 4

2

echo str_replace('X', 'Na', $reactant) ;

Sign up to request clarification or add additional context in comments.

Comments

2

If you're always going to be joining the elements up with a plus sign, you could explode the string as so:

$parts = explode(' + ', $reactant);

Then loop around the array

foreach($parts as &$part) {
    $part = str_replace('X', 'Na', $part);
}

Then to display the results, implode the array back together using the plus:

$reactant = implode(' + ', $parts);

Comments

1

What about just this :

<?php
 $reactant = 'CO2 + H2O + XO';
 $reactant = str_replace('X', 'Na', $reactant);
?>

If you really want to split because your code is longer, you have to set via the key, because the $splitresult will be overwritten after each loop pass. It's a temporary variable. Here is the right way to do it :

<?php
 $reactant = 'CO2 + H2O + XO';
 $products = str_split($reactant);

 foreach($products as $i=>$splitresult)
 {
  $products[$i] = str_replace('X', 'Na', $splitresult) ;
 }
 $reactant = implode('',$products);
?>

Comments

0
<?php
$reactant = 'CO2 + H2O + XO';
$products = explode($reactant, ' + ');

foreach($products as $key => $splitresult)
{
    $products[ $key ] = str_replace('X', 'Na', $splitresult);
}
print_r( $products );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.