Why is the wordwrap function not working as expected in PHP?

The wordwrap function in PHP may not be working as expected if the input string contains HTML tags or special characters that are not being properly handled by the function. To solve this issue, you can use the htmlspecialchars function to encode the input string before passing it to the wordwrap function.

$input_string = "<p>This is a long text that needs to be wrapped</p>";
$wrapped_text = wordwrap(htmlspecialchars($input_string), 50, "<br>", true);

echo $wrapped_text;