Write a function.

Links for php scripts

Moderators: gesf, Michalio

Post Reply
Drummer

Hello everyone. I'm a self learner that is very new to programming.

Write a function(use native php) that accepts an array of opening or closing tags (for example, “<a>”, “</td>”) at the input, and returns the result of the correctness check: i.e. whether the sequence of tags accepted by the function is the structure of a valid HTML document. For example, the sequence “<a>”, “<div>”, “</div>”, “</a>”, “<span>”, “</span>” is the correct structure, and the sequence “<a > ”,“ <div> ”,” </a> ”- incorrect structure.
simonbrahan

Your other two questions were specific enough to just need a single trick to solve; this one is a lot more open ended though. If you're just getting started you might want to look at something simpler.
Strider64

Why write it at all when you simply can validate the HTML Online ?

https://validator.w3.org/
Drummer

That's what I did:

Code: Select all

<?php

function checkTag($tag)
{

    $arr = [];

    $startTag = ['<html>', '<head>', '<body>'];

    $pairsTag = ['<html></html>', '<head></head>', '<body></body>'];


    foreach ($tag as $value) {
        $curr = $value;

        if (in_array($curr, $startTag)) {
            array_push($arr, $curr);
        } else {
            $prev = array_pop($arr);

            $pair = "{$prev}{$curr}";

            if (!in_array($pair, $pairsTag)) {
                return false;
            }
        }
    }


    return count($arr) === 0;
}

var_dump(checkTag(['<head></head>', '<body></body>'])); // true
Post Reply