PHP Strings · Chapter 7.3 · Formatting & Utility

PHP String Functions
sprintf · number_format · str_pad · str_repeat · nl2br

पाँच Formatting और Utility String Functions की पूरी जानकारी — Numbers format करना, strings align करना, patterns repeat करना, और newlines HTML में convert करना।

📐 sprintf() 💰 number_format() ⬜ str_pad() 🔁 str_repeat() ↵ nl2br()
%s %dsprintf specifiers
1,234number_format output
STR_PAD3 padding constants
<br>nl2br output

📋 इस Article में क्या-क्या है

  1. sprintf() — Formatted String
  2. number_format() — Price Format
  3. str_pad() — String Padding
  4. str_repeat() — Repeat करना
  5. nl2br() — Newline to BR
  6. Comparison Table
  7. Combined Invoice Example
1
sprintf() — Formatted String बनाना
spri
ntf

sprintf()

Format string के according एक formatted string बनाता है। Number को fixed decimals में, string को padded format में, integer को hex में — सब possible है।

PHP 4+ Returns: string printf() prints, sprintf() returns
string sprintf( string $format, mixed ...$values )
Format Specifiers — % sign से शुरू होते हैं। सबसे ज़रूरी specifiers:
%s
String

Variable को string की तरह insert करो।

sprintf("%s", "PHP") → PHP
%d
Integer

Integer number insert करो।

sprintf("%d", 42) → 42
%f
Float

Floating point number।

sprintf("%f", 3.14) → 3.140000
%.2f
2 Decimal Float

Fixed 2 decimal places।

sprintf("%.2f", 3.1) → 3.10
%05d
Zero Padded Int

5 chars wide, zeros से pad।

sprintf("%05d", 42) → 00042
%x
Hexadecimal

Integer को hex में convert।

sprintf("%x", 255) → ff
%b
Binary

Integer को binary में।

sprintf("%b", 10) → 1010
%o
Octal

Integer को octal में।

sprintf("%o", 8) → 10
sprintf() — BASIC EXAMPLES
<?php
// 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
?>
sprintf() — REAL WORLD EXAMPLES
<?php
// 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 करता है

// Variable में store कर सकते हो
$msg = sprintf("Hello %s", $naam);
// Email body में use करो
mail($to, "Subject", $msg);

ℹ️ printf() — directly print करता है

// Store नहीं होता — directly output
printf("Hello %s", $naam);
// echo जैसा — but formatted
💡 sprintf vs printf vs echo: sprintf() string return करता है — variable में store, function में pass, database में save कर सकते हो। printf() directly print करता है। 90% cases में sprintf() better है।

2
number_format() — Price और Numbers Format करना
num
fmt

number_format()

Numbers को human-readable format में display करता है — thousands separator (,) और decimal places के साथ। E-commerce में prices display करने के लिए ज़रूरी function है।

PHP 4+ Returns: string E-commerce Must
string number_format(
  float $num,
  int $decimals = 0,
  string $decimal_separator = ".",
  string $thousands_separator = ","
)
ParameterDefaultDescription
$numFormat करने वाला number
$decimals0कितने decimal places चाहिए
$decimal_separator"."Decimal point character
$thousands_separator","Thousands separator character
number_format() — BASIC से ADVANCED
<?php
$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

number_format() — REAL WORLD EXAMPLES
<?php
// 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
?>
⚠️ Common Mistake: number_format() string return करता है — इसके result पर arithmetic operations मत करो। पहले calculation करो, फिर format: $total = $a + $b; echo number_format($total, 2); — न कि format के बाद add।

3
str_pad() — String को Fixed Width बनाना
pad
()

str_pad()

String को किसी character से pad करके एक fixed width बनाता है। Invoice alignment, order numbers, progress bars — neat output के लिए।

PHP 4+ Returns: string 3 Padding Types
string str_pad(
  string $string,
  int $length,
  string $pad_string = " ",
  int $pad_type = STR_PAD_RIGHT
)
ConstantमतलबExample
STR_PAD_RIGHTRight side pad (Default)"Hi " (6 wide)
STR_PAD_LEFTLeft side pad" Hi" (6 wide)
STR_PAD_BOTHदोनों sides pad" Hi " (6 wide)
str_pad() — BASIC EXAMPLES
<?php
$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..............."
?>
str_pad() — REAL WORLD EXAMPLES
<?php
// 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 ============
?>
💡 sprintf vs str_pad: Numbers को zero-pad करने के लिए दोनों काम करते हैं। sprintf("%06d", 42) = str_pad("42", 6, "0", STR_PAD_LEFT) → दोनों "000042" देते हैं। sprintf thoda concise है; str_pad ज़्यादा flexible है custom characters के लिए।

4
str_repeat() — String को Repeat करना
rep
eat

str_repeat()

किसी string को N बार repeat करके return करता है। Separators, decorative lines, masking, HTML elements repeat — simple लेकिन useful function।

PHP 4+ Returns: string Super Simple
string str_repeat( string $string, int $times )
ParameterTypeज़रूरी?Description
$stringstringRequiredजो string repeat करनी है
$timesintRequiredकितनी बार repeat करनी है। 0 = empty string
str_repeat() — BASIC EXAMPLES
<?php
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)
?>
str_repeat() — REAL WORLD EXAMPLES
<?php
// 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("&nbsp;", 5) . "</td>";
?>
✅ Practical Pattern: Star rating के लिए str_repeat("★", $rating) . str_repeat("☆", 5-$rating) — यह एक clean one-liner है। Real projects में इसी तरह use होता है।

5
nl2br() — Newlines को HTML <br> में Convert करना
nl
2br

nl2br()

String में जहाँ-जहाँ newline (\n) है वहाँ <br> tag insert करता है। User का multi-line textarea input HTML में display करने के लिए ज़रूरी है।

PHP 4+ Returns: string Textarea Must
string nl2br( string $string, bool $use_xhtml = true )
ParameterDefaultDescription
$stringInput string जिसमें newlines हैं
$use_xhtmltruetrue = <br />, false = <br>
nl2br() — BASIC EXAMPLES
<?php
$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
?>
nl2br() — REAL WORLD EXAMPLES
<?php
// 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);
?>
⚠️ Security Rule: User का input display करते समय हमेशा htmlspecialchars() पहले, nl2br() बाद में use करो। उल्टा करने पर nl2br की <br> tags भी escape हो जाएंगी।

✅ Correct: nl2br(htmlspecialchars($input))
❌ Wrong: htmlspecialchars(nl2br($input))
CSS Alternative: Modern web में white-space: pre-wrap CSS property भी newlines को respect करती है — nl2br की ज़रूरत नहीं पड़ती। लेकिन nl2br ज़्यादा widely compatible है और HTML emails में CSS always नहीं चलता।

6
Comparison — पाँचों Functions एक नज़र में
FunctionInput ExampleOutputBest 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

7
Combined Example — Invoice Receipt
यह देखो कि एक Invoice page बनाते समय सभी 5 functions एक साथ कैसे काम करते हैं:
COMBINED — Invoice Receipt बनाना
<?php
// 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>";
?>
Invoice pattern: sprintf (IDs) → number_format (prices) → str_pad (alignment) → str_repeat (stars/dividers) → nl2br (customer notes)

निष्कर्ष — Chapter 7 String Series Complete!

Chapter 7.1, 7.2, और 7.3 मिलकर PHP String Functions का complete 15-function toolkit बनाते हैं। यह सब हर real PHP project में daily use होते हैं।

ChapterFunctionsCategory
7.1strlen, strtoupper, strtolower, trim, ucwordsBasic Manipulation
7.2strpos, str_contains, str_replace, substr, explodeSearch & Extract
7.3sprintf, number_format, str_pad, str_repeat, nl2brFormat & 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() बाद।

🚀 अगला Chapter: Chapter 7 String Series complete! अब Chapter 8: PHP Arrays — Indexed Array, Associative Array, Multidimensional Array, और 25+ Array Functions। PHP का सबसे powerful data structure।