0

I have trouble to find the multiple string and replace it with the new string within an array.

this is my array

array (0) = <mfenced><mfrac><mrow><mn>2</mn><mi>x</mi><mo>+</mo><mn>3</mn></mrow><mi>x</mi></mfrac></mfenced>
array (1) = <mfenced><mrow><mn>2</mn><mi>x</mi><mo>+</mo><mn>3</mn></mrow></mfenced>

I need to find <mrow> and look for the next tag, if the next tag is <mo> then I no need to anything, else I need to add <mo>+</mo> next to it.

for example

array (0) = <mfenced><mfrac><mrow><mo>+</mo><mn>2</mn><mi>x</mi><mo>+</mo><mn>3</mn></mrow><mi>x</mi></mfrac></mfenced>
array (1) = <mfenced><mrow><mo>+</mo><mn>2</mn><mi>x</mi><mo>+</mo><mn>3</mn></mrow></mfenced>

this is my current code

$res1=array();
$temp = [];
for ($i=0; $i <count($addplus) ; $i++) { 
    $res1 = $addplus[$i];
     while($pos = strpos($res1, "<mrow>",1))
    {
        if ($pos1=substr($res1,$pos,$pos + 4) != "<mo>")
        {
            $temp=str_replace($pos, "<mrow><mo>+</mo>", $res1);
        }
        else 
        {
            $temp= $res1;
        }         
    }
}
print_r($temp);

$addplus store the array. thank you in advance, have a nice day!

9
  • Why is this tagged javascript? Commented May 28, 2018 at 20:45
  • 2
    Seems like might be easier with an xml parser rather than parsing strings Commented May 28, 2018 at 20:45
  • or a preg_replace with a lookbehind. Commented May 28, 2018 at 20:47
  • @Luca sorry my bad,stackoverflow suggested the tag Commented May 28, 2018 at 20:49
  • 1
    php.net/manual/en/book.simplexml.php Commented May 28, 2018 at 20:54

1 Answer 1

1

How about this?

foreach ($addplus as $key => $string) {
    $t = explode("<mrow>", $string);
    if(substr($t[1], 0, 4) != '<mo>') {
      $addplus[$key] = $t[0].'<mrow><mo>+</mo>'.$t[1];
    }
}

"what if string in array ?i mean appear more than one time"

foreach ($addplus as $key => $string) {
    $t = explode("<mrow>", $string);
    $final = "";
    for($i = 1; $i < count($t); ++$i) {
      if(substr($t[$i], 0, 4) != '<mo>') {
        $final = $final.$t[$i-1].'<mrow><mo>+</mo>'.$t[$i];
      }
      else {
        $final = $final.'<mrow>'.$t[$i];
      }
    }
    $addplus[$key] = $final;
}
Sign up to request clarification or add additional context in comments.

2 Comments

@fismong3r what if string in array ?i mean <mrow> appear more than one time
@jaiwilshere Updated my answer. Had no time to test tough, but you understand the point.

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.