Write a function.

Links for php scripts

Moderators: egami, macek, gesf

Post Reply
User avatar
Drummer
New php-forum User
New php-forum User
Posts: 11
Joined: Thu Dec 17, 2020 12:31 am

Thu Feb 11, 2021 3:10 am

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
php-forum Fan User
php-forum Fan User
Posts: 137
Joined: Mon Jun 08, 2020 2:00 am
Contact:

Thu Feb 11, 2021 4:42 am

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.
User avatar
Strider64
php-forum GURU
php-forum GURU
Posts: 421
Joined: Sat Mar 23, 2013 8:24 am
Location: Livonia, MI
Contact:

Thu Feb 11, 2021 9:51 am

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

https://validator.w3.org/
Life is a fig newton of your imagination! https://www.phototechguru.com/
User avatar
Drummer
New php-forum User
New php-forum User
Posts: 11
Joined: Thu Dec 17, 2020 12:31 am

Thu Feb 11, 2021 9:12 pm

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