When you process a multi-line Hebrew string with both nl2br() and hebrev(), the usual code order might look like this:
echo hebrev(nl2br($text));
This order seems fine, but in the actual output HTML, the
tags may be treated as regular characters by hebrev(), which disrupts the
tags, causing them to appear as invalid strings or even breaking the entire HTML structure.
For example:
$text = "???? ????\n????? ?????";
echo hebrev(nl2br($text));
The output might become:
>rb/<????? ?????<br>???? ????
Note that the
is reversed by hebrev(), turning into >rb/<.
Since hebrev() reverses the entire string to display it in visual order, when the string contains HTML tags such as ,
, or , these tags are also reversed. This causes the page display to be messy or even invalid HTML.
The correct approach is to apply hebrev() first to process the text content, then use nl2br() to insert the HTML tags. This avoids disturbing the HTML tags with hebrev():
echo nl2br(hebrev($text));
In this way, hebrev() only processes the plain text part, and nl2br() then converts the line breaks to
tags without breaking the HTML structure.
hebrev() has a second parameter, $max_chars_per_line, which lets you specify the maximum number of characters per line. Although its main use is for formatting output, setting it to a large value (such as 999) can help minimize unnecessary line breaks:
echo nl2br(hebrev($text, 999));
This is especially useful for texts containing long lines.
If your string already contains HTML tags (for example, from a rich text editor), do not use hebrev() on it. Otherwise, hebrev() may mishandle the HTML tags and break the structure.
One way to handle this is to strip out the HTML tags before processing and then reinsert them afterward, but this is usually complex. Therefore, it is recommended to use hebrev() only on plain text.
Here is a complete example showing how to properly handle multi-line Hebrew text:
<?php
$text = "???? ????\n????? ?????\n?????: https://gitbox.net/page";
echo nl2br(hebrev($text));
?>
The output will preserve the correct
tags and maintain the visual order of Hebrew text, with the domain in the link displayed as gitbox.net.