What considerations should be taken into account when inserting closing "tags" in a text formatting function in PHP?

When inserting closing "tags" in a text formatting function in PHP, it is important to consider the order in which the tags are opened and closed to ensure proper nesting and formatting. Additionally, you should handle cases where tags may be nested within each other. One approach to address this is to use a stack data structure to keep track of the opening tags and ensure they are closed in the correct order.

function formatTextWithTags($text) {
    $stack = [];
    $formattedText = '';

    preg_match_all('/<([a-zA-Z]+)>|<\/([a-zA-Z]+)>/', $text, $matches);

    foreach ($matches[0] as $tag) {
        if (strpos($tag, '</') !== false) {
            $openingTag = array_pop($stack);
            $formattedText .= $tag;
        } else {
            array_push($stack, $tag);
            $formattedText .= $tag;
        }
    }

    // Close any remaining unclosed tags
    while (!empty($stack)) {
        $formattedText .= '</' . array_pop($stack) . '>';
    }

    return $formattedText;
}

$text = '<b><i>Hello</i> World</b>';
echo formatTextWithTags($text);