search
HomeBackend DevelopmentPHP TutorialFix code for HTML tags that are not closed normally (supports nesting and nearby closing)

  1. /**

  2. * fixHtmlTag
  3. *
  4. * html标签修复函数,此函数可以修复未正确闭合的 HTML 标签
  5. *
  6. * 由于不确定性因素太多,暂时提供两种模式“嵌套闭合模式”和
  7. * “就近闭合模式”,应该够用了。
  8. *
  9. * 这两种模式是我为了解释清楚此函数的实现而创造的两个名词,
  10. * 只需明白什么意思就行。
  11. * 1,嵌套闭合模式,NEST,为默认的闭合方式。即 "
    你好"
  12. * 这样的 html 代码会被修改为 "
    你好
    "
  13. * 2. Nearby closing mode, CLOSE. This mode will modify the code in the form of "

    Hello

    Why is there no

  14. * closed?" to "

    Why is it not closed

    "
  15. *
  16. * In the nested closing mode (default, no special parameters are required), you can pass in the
  17. * that needs to be closed nearby Tag name, in this way, something like "

    Hello

    Me, too" will be converted into

  18. * "

    Hello

    I also like the form of

    ".
  19. * When passing parameters, the index needs to be written as follows. Settings that do not need to be modified can be omitted
  20. *
  21. * $param = array(
  22. * 'html' => '', //Required
  23. * 'options' => ; array(
  24. * 'tagArray' => array();
  25. * 'type' => 'NEST',
  26. * 'length' => null,
  27. * 'lowerTag' => TRUE,
  28. * ' XHtmlFix' => TRUE,
  29. * )
  30. * );
  31. * fixHtmlTag($param);
  32. *
  33. * The meaning of the value corresponding to the above index is as follows
  34. * string $html The html code that needs to be modified
  35. * array $tagArray shall be When nesting mode, the nearest closed tag array is required
  36. * string $type mode name, currently supports two modes: NEST and CLOSE. If set to CLOSE, the setting of the parameter $tagArray will be ignored, and all tags will be closed at the nearest
  37. * ini $length If you want to truncate a certain length, you can assign a value here. This length refers to the length of the string.
  38. * bool $lowerTag Whether to convert all tags in the code to lowercase, the default is TRUE
  39. * bool $XHtmlFix Whether to handle inconsistencies XHTML standard tags, that is, converting
    to
  40. *
  41. * @author IT卤场
  42. * @version 0.2
  43. * @link http://bbs.it -home.org IT tumbler
  44. * @link http://enenba.com/?post=19 XX
  45. * @param array $param array parameter, which needs to be assigned a specific index
  46. * @return string $result processed html code
  47. * @since 2012-04-14
  48. */
  49. function fixHtmlTag($param = array()) {
  50. //Default value of parameter
  51. $html = '';
  52. $tagArray = array();
  53. $ type = 'NEST';
  54. $length = null;
  55. $lowerTag = TRUE;
  56. $XHtmlFix = TRUE;
  57. //First get the one-dimensional array, that is, $html and $options (if Parameters are provided)

  58. extract($param);
  59. //If options exist, extract relevant variables

  60. if (isset($options)) {
  61. extract($options);
  62. }< ;/p>
  63. $result = ''; //The final html code to be returned

  64. $tagStack = array(); //Tag stack, simulated with array_push() and array_pop()
  65. $contents = array(); //Used to store html tags
  66. $len = 0; //Initial length of the string
  67. //Set the closing mark $isClosed, the default is TRUE, if you need to close it nearby , after successfully matching the start tag, its value is false, and after successful closing, it is true

  68. $isClosed = true;
  69. //Convert all tags to be processed to lowercase

  70. $tagArray = array_map('strtolower ', $tagArray);
  71. //"Legal" single closed tag

  72. $singleTagArray = array(
  73. ''''
    '
    ''Fix code for HTML tags that are not closed normally (supports nesting and nearby closing));
  74. //Verification matching pattern $type , the default is NEST mode

  75. $type = strtoupper($type);
  76. if (!in_array($type, array('NEST', 'CLOSE'))) {
  77. $type = 'NEST';
  78. } p>
  79. //Using a pair of as delimiters, put the original html tag and the string in the tag into an array

  80. $contents = preg_split("/( ]+?>)/si", $html, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
  81. foreach ($contents as $tag) {

  82. if ('' == trim($ tag)) {
  83. $result .= $tag;
  84. continue;
  85. }
  86. //Match standard single closed tags, such as

  87. if (preg_match("/ ]*?/>/si", $tag)) {
  88. $result .= $tag;
  89. continue;
  90. }
  91. // Match the start tag, if it is a single tag, pop it off the stack

  92. else if (preg_match("/]*?>/si", $tag, $match)) {
  93. //if The previous label is not closed, and the previous label belongs to the nearest closed type
  94. //Close it, and pop the previous label
  95. //If the label is not closed

  96. if (false === $ isClosed) {
  97. //Close close mode, close all tags directly
  98. if ('CLOSE' == $type) {
  99. $result .= '' . end($tagStack) . '>';
  100. array_pop($tagStack);
  101. }
  102. //Default nesting mode, the tag provided by the nearest closing parameter
  103. else {
  104. if (in_array(end($tagStack), $tagArray)) {
  105. $result .= '< ;/' . end($tagStack) . '>';
  106. array_pop($tagStack);
  107. }
  108. }
  109. }
  110. //If the parameter $lowerTag is TRUE, convert the tag name to lowercase

  111. $matchLower = $lowerTag == TRUE ? strtolower($match[1]) : $match[1];
  112. $tag = str_replace('//Start a new tag combination

  113. $result . = $tag;
  114. array_push($tagStack, $matchLower);
  115. //If it belongs to the agreed single tag, close it and pop it out of the stack

  116. foreach ($singleTagArray as $singleTag) {
  117. if (stripos($tag, $singleTag) !== false) {
  118. if ($XHtmlFix == TRUE) {
  119. $tag = str_replace('>', ' />', $tag);
  120. }
  121. array_pop($tagStack);
  122. }
  123. }
  124. //Nearby closed mode, status changes to unclosed

  125. if ('CLOSE' == $type) {
  126. $isClosed = false;
  127. }
  128. //Default nesting mode, if the tag is located in the provided $tagArray, the status is changed to unclosed
  129. else {
  130. if (in_array($matchLower, $tagArray)) {
  131. $isClosed = false;
  132. }
  133. }
  134. unset($matchLower);
  135. }
  136. //Match the closing tag and pop it off the stack if appropriate

  137. else if (preg_match("/(w+)[^/> ]*?>/si", $tag, $match)) {
  138. //If the parameter $lowerTag is TRUE, convert the tag name to lowercase

  139. $matchLower = $lowerTag == TRUE ? strtolower($match[1]) : $match[1];
  140. if (end($tagStack) == $matchLower) {

  141. $isClosed = true; //Match completed , tag closure
  142. $tag = str_replace('' . $match[1], '' . $matchLower, $tag);
  143. $result .= $tag;
  144. array_pop($tagStack);
  145. }
  146. unset($matchLower);
  147. }
  148. //Match comments, directly connect $result

  149. else if (preg_match("// si", $tag)) {
  150. $result .= $tag;
  151. }
  152. //Put the string into $result and do the truncation operation

  153. else {
  154. if (is_null ($length) || $len + mb_strlen($tag) $result .= $tag;
  155. $len += mb_strlen($tag);
  156. } else {
  157. $str = mb_substr($ tag, 0, $length - $len + 1);
  158. $result .= $str;
  159. break;
  160. }
  161. }
  162. }
  163. //If there are still unused items in the stack The closed tag is connected to $result

  164. while (!empty($tagStack)) {
  165. $result .= '' . array_pop($tagStack) . '>';
  166. }
  167. return $result;
  168. }
  169. ?>
Copy code


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

How does using HTTPS affect session security?How does using HTTPS affect session security?Apr 22, 2025 pm 05:13 PM

HTTPS significantly improves the security of sessions by encrypting data transmission, preventing man-in-the-middle attacks and providing authentication. 1) Encrypted data transmission: HTTPS uses SSL/TLS protocol to encrypt data to ensure that the data is not stolen or tampered during transmission. 2) Prevent man-in-the-middle attacks: Through the SSL/TLS handshake process, the client verifies the server certificate to ensure the connection legitimacy. 3) Provide authentication: HTTPS ensures that the connection is a legitimate server and protects data integrity and confidentiality.

The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools