.
This wonderful little PHP function searches through a string containing HTML elements, locates all the HTML tags, closes any that are open, and returns the string. We can’t take much credit for this given that we only modified what was originally done by another talented programmer (who we regrettably can’t credit due to a lack of details). However, it took us a little time to get something that worked just right.
This has been best deployed when using integrated text editors like Yahoo YUI 2: Rich Text Editor that typically leave tags open during user editing. We hope it will be just as useful for you as it has for the My PerPOS web architecture.
| PHP | | copy code | | ? |
- function closetags($html) {
- // Put all opened tags into an array
- preg_match_all('#<([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
- $openedtags = $result[1]; #put all closed tags into an array
- preg_match_all('#</([a-z]+)>#iU', $html, $result);
- $closedtags = $result[1];
- $len_opened = count($openedtags);
- # Check if all tags are closed
- if (count($closedtags) == $len_opened){
- return $html;
- }
- $openedtags = array_reverse($openedtags);
- # close tags
- for ($i=0; $i < $len_opened; $i++) {
- if (!in_array($openedtags[$i], $closedtags)){
- if($openedtags[$i]!='br'){
- // Ignores <br> tags to avoid unnessary spacing
- // at the end of the string
- $html .= '</'.$openedtags[$i].'>';
- }
- } else {
- unset($closedtags[array_search($openedtags[$i], $closedtags)]);
- }
- }
- return $html;
- }
Usage:
| PHP | | copy code | | ? |
- $withclosedtags = closetags("<your_string_with_html>");