php名目化html函数

此函数从wp中提取出来的,可以或许名目化html,让html标签缩进,增加输出html的可读性。

上源码:

<?php /** * Merge user defined arguments into defaults array. * * This function is used throughout WordPress to allow for both string or array * to be merged into another array. * * @since 2.2.0 * * @param string|array $args Value to merge with $defaults * @param array $defaults Array that serves as the defaults. * @return array Merged user defined values with defaults. */ function wp_parse_args( $args, $defaults = '' ) { if ( is_object( $args ) ) $r = get_object_vars( $args ); elseif ( is_array( $args ) ) $r =& $args; else wp_parse_str( $args, $r ); if ( is_array( $defaults ) ) return array_merge( $defaults, $r ); return $r; } /** * (PHP) * Description: 此代码可以用来名目化html文本或包括有如<tags></tags>形式的代码 * * (string) _code_format($args); * * $args = array( * 'code' => '', * 'indent' => 0, * 'offset' => false, * 'echo' => true, * ); * * Parameters: * $code * (string) 需要名目化的文本 * Default: None * $indent * (bool) 代码插入前是否已举办过缩进 * Default: false * $offset * (int) 整体缩进量。如:1暗示每行前多加一个Tab符 * Default: 0 * $echo * (bool) 是否显示名目化后的文本 * Default: true * * 无论$echo为true照旧false,函数返回名目化后的文本 * * Example: * _code_format(array( * 'code' => '<div>Hello<span>World!</span><img src="http://enenba.com/sample.jpg" /></div><div>', * 'offset' => 2 * )); * */ function _code_format($args = array()) { $defaults = array('code' => '', 'indent' => false, 'offset' => 0, 'echo' => true); $args = wp_parse_args($args, $defaults); $args = (object) $args; $code = str_replace(array("\n", "\t"), '', $args->code); $indent = ''; for ($i = 0; $i < $args->offset; $i++) { $indent .= "\t"; } $pattern = "/<[\w]+[^>]*>[^<]*|<\/[\w]+>[^<]*/"; while (preg_match($pattern, $code, $matches)) { if (substr($matches[0], -2, 1) != '/') { if (substr($matches[0], 1, 1) != '/') { $format_code .= "\n" . $indent . $matches[0]; $indent = $indent . "\t"; $tag_flag = true; } else { if ($tag_flag) { $format_code .= $matches[0]; $indent = substr($indent, 0, -1); } else { $indent = substr($indent, 0, -1); $format_code .= "\n" . $indent . $matches[0]; } $tag_flag = false; } } else { $format_code .= $matches[0]; } $code = preg_replace("/" . str_replace('/', '\/', $matches[0]) . "/", '', $code, 1); } if ($args->indent) $format_code = preg_replace("/\t/", '', $format_code, $args->offset); $format_code = preg_replace("/\n/", '', $format_code, 1) . "\n"; if ($args->echo) echo $format_code; return $format_code; } ?>

经测试会有机能上的问题,请谨用!!

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/7856.html