Question:

HTML Validation in PHP

by  |  earlier

0 LIKES UnLike

Hi,

If some one can point me into right direction or give me an example.

What i need:

I need to make HTML validation tool to sure that HTML tags in it are properly closed with closing tag '</tag>' (except standalone tags) and that tags that are opened with '<' properly closed with '>' For example:

Correct: <b>Text</b>

Catch: <b Text</b> or <b>Text /b> or <b>Text

Thank you!

 Tags:

   Report

2 ANSWERS


  1. Why don&#039;t you just Google &#039;HTML Validation in PHP&#039; or is that too difficult?


  2. &lt;?php

    if ($argc != 2) {

    echo &quot;Usage: $argv[0] &lt;HTML_filename&gt;\n&quot;;

    exit();

    }

    $html = file_get_contents($argv[1]);

    $html_split = explode(&#039;&lt;&#039;, $html);

    $tags = array();

    foreach($html_split as $inx =&gt; $potential_tag) {

    $gt = strpos($potential_tag, &#039;&gt;&#039;);

    if ($gt === false) {

    if ($inx) echo &#039;&lt;&#039;.$potential_tag.&quot;\n&quot;;

    } else {

    if ($inx) $tags[] = &#039;&lt;&#039;.substr($potential_tag, 0, $gt + 1);

    else echo substr($potential_tag, 0, $gt + 1).&quot;\n&quot;;

    }

    }

    for($inx = 0; $inx &lt; count($tags); $inx++) {

    $tag = strtolower($tags[$inx]);

    for($i = 0; $i &lt; strlen($tag); $i++) {

    $c = substr($tag, $i, 1);

    if ($c &lt; &#039;a&#039; || $c &gt; &#039;z&#039;) {

    $tag_type = substr($tag, 1, $i - 1);

    if (substr($tag, -2) == &#039;/&gt;&#039;) {

    $tags = array_merge(array_slice($tags, 0, $inx), array_slice($tags, $inx + 1));

    $inx--;

    $i = strlen($tag);

    } elseif (match_tag($tag_type, $tags, $inx)) {

    $tags = array_merge(array_slice($tags, 0, $inx), array_slice($tags, $inx + 1));

    $inx--;

    $i = strlen($tag);

    } else echo $tag.&quot; (unclosed)\n&quot;;

    }

    }

    }

    function match_tag($type, &amp;$tags, $inx) {

    for($i = count($tags) - 1; $i &gt; $inx; $i--) {

    if ($tags[$i] == &#039;&lt;/&#039;.$type.&#039;&gt;&#039;) {

    $tags = array_merge(array_slice($tags, 0, $i), array_slice($tags, $i + 1));

    return true;

    }

    }

    return false;

    }

    ?&gt;

You're reading: HTML Validation in PHP

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions