PHP में string से newline characters (\n, \r, \r\n) remove करने के तरीके।
विधि 1: preg_replace() - सभी Line Endings
<?php
$str = "Line 1\nLine 2\r\nLine 3\rLine 4";
// सभी line endings remove करें
$result = preg_replace('/\r\n|\r|\n/', '', $str);
// या shorthand
$result = preg_replace('/\R/', '', $str); // \R = any Unicode newline
echo $result; // Line 1Line 2Line 3Line 4
विधि 2: str_replace() - Array के साथ (Fast, No Regex)
<?php $str = "Line 1\nLine 2\r\nLine 3"; // Replace multiple patterns $result = str_replace(["\r\n", "\n", "\r"], '', $str); echo $result; // Line 1Line 2Line 3 // Order matters: \r\n पहले replace करें!
विधि 3: Single Space के साथ Replace (Readability)
<?php
$str = "Line 1\n\nLine 2\r\nLine 3";
// Newlines को single space से replace
$result = preg_replace('/\R+/', ' ', $str);
echo $result; // Line 1 Line 2 Line 3
// Multiple spaces collapse करें
$result = preg_replace('/\s+/', ' ', $str);
विधि 4: nl2br() Reverse (HTML Context)
<?php // यदि HTML में
tags हैं और plain text चाहिए $html = "Line 1
\nLine 2
Line 3"; $text = strip_tags($html); //
remove करता है लेकिन \n छोड़ सकता है $text = preg_replace('/\R+/', ' ', $text); // Clean up
तुलना
| विधि | Speed | Handles \r\n | Handles \r | Use Case |
|---|---|---|---|---|
preg_replace('/\R/') | मध्यम | ✅ | ✅ | सभी Unicode line endings |
str_replace([...]) | तेज़ | ✅ (यदि पहले) | ✅ | Simple ASCII, performance critical |
preg_replace('/\s+/') | धीमा | ✅ | ✅ | All whitespace collapse |
व्यावहारिक उदाहरण
<?php
// 1. Textarea input normalize करें
function normalizeTextarea($input) {
// Windows/Mac/Unix line endings normalize
$input = str_replace("\r\n", "\n", $input); // Windows → Unix
$input = str_replace("\r", "\n", $input); // Old Mac → Unix
return $input;
}
// 2. CSV/Log parsing के लिए lines में split
function splitLines($text) {
return preg_split('/\R+/', trim($text));
}
// 3. HTML output के लिए
में convert
function nl2brSafe($text) {
return nl2br(htmlspecialchars($text));
}
// 4. Remove empty lines
function removeEmptyLines($text) {
return preg_replace('/\R\s*\R/', "\n", $text); // Double+ newlines को single में
}
Constants Reference
<?php
// PHP predefined constants
echo PHP_EOL; // Current platform की line ending (\n या \r\n)
// PHP_OS: WINNT, Linux, Darwin, आदि
// Manual definitions
define('LF', "\n"); // Line Feed (Unix, Linux, macOS)
define('CR', "\r"); // Carriage Return (old Mac)
define('CRLF', "\r\n"); // Carriage Return + Line Feed (Windows)