PHP String Functions
sprintf · number_format · str_pad · str_repeat · nl2br
पाँच Formatting और Utility String Functions की पूरी जानकारी — Numbers format करना, strings align करना, patterns repeat करना, और newlines HTML में convert करना।
📋 इस Article में क्या-क्या है
- sprintf() — Formatted String
- number_format() — Price Format
- str_pad() — String Padding
- str_repeat() — Repeat करना
- nl2br() — Newline to BR
- Comparison Table
- Combined Invoice Example
String
Variable को string की तरह insert करो।
sprintf("%s", "PHP") → PHPInteger
Integer number insert करो।
sprintf("%d", 42) → 42Float
Floating point number।
sprintf("%f", 3.14) → 3.1400002 Decimal Float
Fixed 2 decimal places।
sprintf("%.2f", 3.1) → 3.10Zero Padded Int
5 chars wide, zeros से pad।
sprintf("%05d", 42) → 00042Hexadecimal
Integer को hex में convert।
sprintf("%x", 255) → ffBinary
Integer को binary में।
sprintf("%b", 10) → 1010Octal
Integer को octal में।
sprintf("%o", 8) → 10// Basic string insert
echo sprintf("Hello, %s!", "Rahul");
// Hello, Rahul!
// Multiple values
echo sprintf("नाम: %s, उम्र: %d साल", "Rahul", 25);
// नाम: Rahul, उम्र: 25 साल
// Float precision
echo sprintf("Price: %.2f", 99.5); // Price: 99.50
echo sprintf("PI: %.4f", 3.14159); // PI: 3.1416
// Zero padding
echo sprintf("%05d", 42); // 00042
echo sprintf("%08d", 1234); // 00001234
// Hex, Binary, Octal
echo sprintf("%x", 255); // ff
echo sprintf("%X", 255); // FF (uppercase)
echo sprintf("%b", 10); // 1010
?>
// 1. Order ID generate करना — ORD-00001
$orderId = 42;
echo sprintf("ORD-%05d", $orderId); // ORD-00042
// 2. Percentage format करना
$score = 87.666;
echo sprintf("आपका score: %.1f%%", $score);
// आपका score: 87.7% (%% = literal %)
// 3. Invoice line item
$item = "PHP Book";
$qty = 2;
$price = 450.5;
$total = $qty * $price;
echo sprintf("%-20s %3d x %8.2f = %10.2f", $item, $qty, $price, $total);
// PHP Book 2 x 450.50 = 901.00
// 4. CSS hex color बनाना
$r = 255; $g = 128; $b = 0;
echo sprintf("#%02x%02x%02x", $r, $g, $b);
// #ff8000
// 5. Argument swapping — %1$s, %2$s
echo sprintf("%2\$s को %1\$s पसंद है", "PHP", "Rahul");
// Rahul को PHP पसंद है (order swap!)
?>
✅ sprintf() — string return करता है
$msg = sprintf("Hello %s", $naam);
// Email body में use करो
mail($to, "Subject", $msg);
ℹ️ printf() — directly print करता है
printf("Hello %s", $naam);
// echo जैसा — but formatted
float $num,
int $decimals = 0,
string $decimal_separator = ".",
string $thousands_separator = ","
)
| Parameter | Default | Description |
|---|---|---|
| $num | — | Format करने वाला number |
| $decimals | 0 | कितने decimal places चाहिए |
| $decimal_separator | "." | Decimal point character |
| $thousands_separator | "," | Thousands separator character |
$price = 1234567.891;
// Param 1 only — integer, commas
echo number_format($price);
// 1,234,568 (rounded)
// 2 decimal places
echo number_format($price, 2);
// 1,234,567.89
// Indian style — . decimal, , thousands
echo number_format($price, 2, ".", ",");
// 1,234,567.89
// European style — , decimal, . thousands
echo number_format($price, 2, ",", ".");
// 1.234.567,89
// Space separator — French style
echo number_format($price, 2, ",", " ");
// 1 234 567,89
?>
Product Price
₹1,299.00 format
Statistics
1,50,000 users
Invoice Total
Grand Total: ₹45,670.50
Financial Data
Revenue: ₹12,34,567
// 1. E-commerce product price
$price = 1299;
$discount = 199.50;
$final = $price - $discount;
echo "MRP: ₹" . number_format($price, 2); // ₹1,299.00
echo "Offer: ₹" . number_format($final, 2); // ₹1,099.50
// 2. GST calculation display
$base = 10000;
$gst = $base * 0.18;
$total = $base + $gst;
echo "Base Amount : ₹" . number_format($base, 2); // ₹10,000.00
echo "GST (18%) : ₹" . number_format($gst, 2); // ₹1,800.00
echo "Total : ₹" . number_format($total, 2); // ₹11,800.00
// 3. Discount percentage
$original = 2000;
$sale = 1500;
$discountPct = (($original - $sale) / $original) * 100;
echo number_format($discountPct, 1) . "% OFF";
// 25.0% OFF
?>
string $string,
int $length,
string $pad_string = " ",
int $pad_type = STR_PAD_RIGHT
)
| Constant | मतलब | Example |
|---|---|---|
| STR_PAD_RIGHT | Right side pad (Default) | "Hi " (6 wide) |
| STR_PAD_LEFT | Left side pad | " Hi" (6 wide) |
| STR_PAD_BOTH | दोनों sides pad | " Hi " (6 wide) |
$str = "PHP"; // 3 chars
// Right pad (default) — spaces add होते हैं right में
echo str_pad($str, 10); // "PHP " (7 spaces)
// Left pad — numbers align करने के लिए
echo str_pad($str, 10, " ", STR_PAD_LEFT); // " PHP"
// Both sides — center alignment
echo str_pad($str, 10, " ", STR_PAD_BOTH); // " PHP "
// Custom pad character — zeros
echo str_pad("42", 6, "0", STR_PAD_LEFT); // "000042"
// Custom pad character — dots
echo str_pad("Total", 20, "."); // "Total..............."
?>
// 1. Invoice — aligned columns (plain text)
$items = [
["PHP Book", 450],
["Laravel Guide", 799],
["MySQL Notes", 299],
];
foreach ($items as [$name, $price]) {
echo str_pad($name, 20) .
str_pad("₹" . $price, 10, " ", STR_PAD_LEFT) . "\n";
}
// PHP Book ₹450
// Laravel Guide ₹799
// MySQL Notes ₹299
// 2. Order number — ORD-000042
$ordNum = 42;
echo "ORD-" . str_pad($ordNum, 6, "0", STR_PAD_LEFT);
// ORD-000042
// 3. Progress bar बनाना
$percent = 65;
$filled = str_pad("", $percent, "█");
$empty = str_pad("", 100 - $percent, "░");
echo "[" . $filled . $empty . "] " . $percent . "%";
// [█████████████████████████████████████████████████████████████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░] 65%
// 4. Centered heading
$heading = " PHP Tutorial ";
echo str_pad($heading, 40, "=", STR_PAD_BOTH);
// ============ PHP Tutorial ============
?>
| Parameter | Type | ज़रूरी? | Description |
|---|---|---|---|
| $string | string | Required | जो string repeat करनी है |
| $times | int | Required | कितनी बार repeat करनी है। 0 = empty string |
echo str_repeat("ab", 4); // abababab
echo str_repeat("*", 10); // **********
echo str_repeat("-", 30); // ------------------------------ (30 dashes)
echo str_repeat("🌟", 5); // 🌟🌟🌟🌟🌟
echo str_repeat("Ha", 3); // HaHaHa
echo str_repeat("x", 0); // "" (empty string)
?>
// 1. Star rating display
$rating = 4;
$maxStars = 5;
$stars = str_repeat("★", $rating) . str_repeat("☆", $maxStars - $rating);
echo $stars; // ★★★★☆
// 2. Password masking
$password = "mypass123";
$masked = str_repeat("*", strlen($password));
echo $masked; // ********* (9 stars)
// 3. Section divider
echo str_repeat("=", 50) . "\n";
echo " PHP Tutorial — Chapter 7\n";
echo str_repeat("=", 50) . "\n";
// 4. Indentation बनाना
$level = 3;
$indent = str_repeat(" ", $level); // 6 spaces
echo $indent . "- Sub item"; // " - Sub item"
// 5. Simple HTML table separator
echo "<td>" . str_repeat(" ", 5) . "</td>";
?>
| Parameter | Default | Description |
|---|---|---|
| $string | — | Input string जिसमें newlines हैं |
| $use_xhtml | true | true = <br />, false = <br> |
$text = "Line 1\nLine 2\nLine 3";
// Without nl2br — browser में सब एक line में दिखेगा
echo $text;
// Output: Line 1 Line 2 Line 3 (एक line में)
// With nl2br — proper line breaks
echo nl2br($text);
// Output: Line 1<br />Line 2<br />Line 3
// Browser में: तीन अलग lines
// XHTML false — <br> (HTML5 style)
echo nl2br($text, false);
// Line 1<br>Line 2<br>Line 3
?>
// 1. Textarea comment display — सबसे common use
// User ने textarea में enter press करके लिखा:
$comment = "PHP बहुत अच्छी language है।\nमैंने इसे 3 महीने में सीखा।\nअब मैं projects बना सकता हूँ।";
// Safe display — htmlspecialchars + nl2br
$safeComment = nl2br(htmlspecialchars($comment));
echo "<p>" . $safeComment . "</p>";
// PHP बहुत अच्छी language है।<br />
// मैंने इसे 3 महीने में सीखा।<br />
// अब मैं projects बना सकता हूँ।
// 2. Email body display करना
$emailBody = "Dear Rahul,\n\nआपकी payment successful है।\nOrder ID: ORD-00042\n\nThank you!";
echo "<div class='email'>" . nl2br(htmlspecialchars($emailBody)) . "</div>";
// 3. Address format करना
$address = "Flat 5, Block B\nMG Road\nNew Delhi - 110001";
echo nl2br($address);
?>
✅ Correct: nl2br(htmlspecialchars($input))
❌ Wrong: htmlspecialchars(nl2br($input))
| Function | Input Example | Output | Best Use Case |
|---|---|---|---|
| sprintf() | sprintf("%.2f", 99.5) | "99.50" | Order IDs, prices, formatted messages |
| number_format() | number_format(1234.5, 2) | "1,234.50" | E-commerce prices, financial data |
| str_pad() | str_pad("42", 6, "0", LEFT) | "000042" | Invoice alignment, progress bar |
| str_repeat() | str_repeat("★", 4) | "★★★★" | Star ratings, dividers, masking |
| nl2br() | nl2br("Hi\nThere") | "Hi<br />There" | Textarea comments, email display |
// Order data
$orderId = 42;
$customer = "Rahul Kumar";
$rating = 4;
$note = "Fast delivery.\nProduct quality is good.\nWill order again.";
$items = [
["PHP Book", 2, 450.00],
["Laravel Guide", 1, 799.00],
];
// 1. sprintf — Order ID format
$formattedId = sprintf("ORD-%06d", $orderId);
// ORD-000042
// 2. str_repeat — divider बनाना
$divider = str_repeat("-", 40);
// 3. str_pad + number_format — item lines
$subtotal = 0;
$lines = "";
foreach ($items as [$name, $qty, $price]) {
$lineTotal = $qty * $price;
$subtotal += $lineTotal;
$lines .= str_pad($name, 18)
. str_pad($qty . "x", 5)
. str_pad("₹" . number_format($lineTotal, 2), 12, " ", STR_PAD_LEFT)
. "\n";
}
// 4. number_format — totals
$gst = $subtotal * 0.18;
$total = $subtotal + $gst;
// 5. str_repeat — star rating
$stars = str_repeat("★", $rating) . str_repeat("☆", 5 - $rating);
// 6. nl2br — customer note
$safeNote = nl2br(htmlspecialchars($note));
// Output
echo "<pre>";
echo sprintf("Order: %s | Customer: %s\n", $formattedId, $customer);
echo $divider . "\n" . $lines . $divider . "\n";
echo str_pad("Subtotal:", 28) . "₹" . number_format($subtotal, 2) . "\n";
echo str_pad("GST 18%:", 28) . "₹" . number_format($gst, 2) . "\n";
echo str_pad("TOTAL:", 28) . "₹" . number_format($total, 2) . "\n";
echo "Rating: " . $stars . "\n";
echo "</pre>";
echo "<p>Note: " . $safeNote . "</p>";
?>
Chapter 7.1, 7.2, और 7.3 मिलकर PHP String Functions का complete 15-function toolkit बनाते हैं। यह सब हर real PHP project में daily use होते हैं।
| Chapter | Functions | Category |
|---|---|---|
| 7.1 | strlen, strtoupper, strtolower, trim, ucwords | Basic Manipulation |
| 7.2 | strpos, str_contains, str_replace, substr, explode | Search & Extract |
| 7.3 | sprintf, number_format, str_pad, str_repeat, nl2br | Format & Utility |
sprintf() — formatted string। Order IDs, prices, hex colors।
number_format() — E-commerce prices। हमेशा 2 decimals के साथ।
str_pad() — alignment। Left pad = numbers, Right pad = text।
str_repeat() — stars, dividers, masking। Simple but useful।
nl2br() — textarea input display। htmlspecialchars() पहले, nl2br() बाद।