When working with PHP, nl2br can help with a specific task: inserts HTML line-break tags before newline characters.
This guide shows what nl2br does, how to use it in code, and which details you should check before relying on the result.
What Is nl2br in PHP?
Inserts HTML line-break tags before newline characters.
Usage: The following examples show calls with suitable values. Consult the function parameters described in the examples, especially when optional arguments or extensions are involved.
Example 1: Basic Usage
The first example introduces nl2br with a direct PHP expression.
<?php
echo nl2br("First
Second");
Observe the value returned or printed by nl2br and compare it with the input used in this example.
Example 2: A Different Input or Option
This second example demonstrates another input or condition, so you can compare the behavior with the first example.
<?php
echo nl2br("A
B", false);
Observe the value returned or printed by nl2br and compare it with the input used in this example.
Practical Example
Here is a small scenario illustrating how nl2br can fit into application code. Run the example only in an appropriate development environment if it reads files, changes data, starts processes or connects to a service.
<?php
$comment = "Hello <script>alert(1)</script>
Next line"; echo nl2br(htmlspecialchars($comment, ENT_QUOTES, "UTF-8"));
Observe the value returned or printed by nl2br and compare it with the input used in this example.
Important Behavior and Edge Cases
- Core behavior: Inserts HTML line-break tags before newline characters.
- Important limitation: nl2br() does not escape HTML; apply htmlspecialchars() first to untrusted text.
- Production use: Check return values and handle failures before acting on the result.
Comparison With Related Functions
| Function or Approach | Difference |
|---|---|
nl2br() | Inserts HTML line-break tags before newline characters. |
htmlspecialchars() | Related approach. Its purpose and return value differ; select it when your task matches that operation. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
Overlooking a special case of nl2br(). | nl2br() does not escape HTML; apply htmlspecialchars() first to untrusted text. |
Using nl2br() without checking the outcome. | Handle failures and confirm that the output is suitable for the next step. |
Key Takeaways
- Inserts HTML line-break tags before newline characters.
- nl2br() does not escape HTML; apply htmlspecialchars() first to untrusted text.
- Test the function with relevant inputs before using it in production.
Use nl2br when its behavior matches the job you need to complete. For dependable results, consider the input data, returned value and limitations shown above.