PHP में string से spaces remove करने के कई तरीके हैं, आवश्यकता के अनुसार।
विधि 1: str_replace() - केवल Spaces (सबसे तेज़)
<?php
$str = "this is a test string";
$result = str_replace(' ', '', $str);
echo $result; // thisisateststring
विधि 2: strtr() - Multiple Characters
<?php $str = "this is a test string"; // Array syntax: ['from' => 'to'] $result = strtr($str, [' ' => '', "\t" => '', "\n" => '']); echo $result; // thisisateststring
विधि 3: preg_replace() - All Whitespace (Regex)
<?php
$str = "this\tis\na test\r\nstring";
// \s matches: space, tab, newline, carriage return, vertical tab, form feed
$result = preg_replace('/\s+/', '', $str);
echo $result; // thisisateststring
// या केवल spaces और tabs
$result = preg_replace('/[ \t]+/', '', $str);
विधि 4: str_split + implode (Character-level control)
<?php
$str = "this is a test";
// Filter out whitespace characters
$result = implode('', array_filter(str_split($str), function($char) {
return !ctype_space($char);
}));
echo $result; // thisisatest
तुलना तालिका
| विधि | Removes | Speed | Use Case |
|---|---|---|---|
str_replace(' ', '') | केवल space ( ) | सबसे तेज़ | Simple space removal |
strtr() | Specified chars | तेज़ | Multiple specific chars |
preg_replace('/\s+/') | सभी whitespace | धीमा | Complete whitespace removal |
preg_replace('/\h+/') | Horizontal whitespace | धीमा | Spaces + tabs only |
preg_replace('/\v+/') | Vertical whitespace | धीमा | Newlines only |
Whitespace Characters Reference
\s = [ \t\r\n\v\f] // All whitespace \h = [ \t] // Horizontal (space, tab) \v = [\r\n\v\f] // Vertical (newlines, etc.)
व्यावहारिक उदाहरण
<?php
// 1. User input sanitization (keep single spaces between words)
function normalizeSpaces($str) {
return preg_replace('/\s+/', ' ', trim($str));
}
// 2. Remove all whitespace for comparison
function compareIgnoreWhitespace($a, $b) {
return preg_replace('/\s+/', '', $a) === preg_replace('/\s+/', '', $b);
}
// 3. CSS/JS minification (basic)
function minifyCss($css) {
$css = preg_replace('/\s+/', ' ', $css); // Collapse whitespace
$css = preg_replace('/\s*([{}:;,])\s*/', '$1', $css); // Remove around punctuation
return trim($css);
}
// 4. Phone number cleaning
function cleanPhone($phone) {
return preg_replace('/\D/', '', $phone); // Keep only digits
}
महत्वपूर्ण नोट
trim()केवल string के शुरुआत और अंत से whitespace हटाता है, बीच से नहीं। बीच के spaces के लिए ऊपर दिए गए तरीके उपयोग करें।