Reputation: 2657
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;
Upvotes: 0
Views: 69
Reputation: 70
<?php
$reactant = 'CO2 + H2O + XO';
$products = explode($reactant, ' + ');
foreach($products as $key => $splitresult)
{
$products[ $key ] = str_replace('X', 'Na', $splitresult);
}
print_r( $products );
Upvotes: 0
Reputation: 1596
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);
?>
Upvotes: 1
Reputation: 3582
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);
Upvotes: 2