PHP Strings · Chapter 7.4 · Split & Transform

PHP String Functions
strrev · str_word_count · wordwrap · chunk_split · str_split

String को reverse करना, words count करना, wrap करना, chunks में तोड़ना, और array में split करना — पाँच powerful transformation functions।

🔁 strrev() 🔢 str_word_count() ↩️ wordwrap() ✂️ chunk_split() 📦 str_split()
strrevPalindrome check
3str_word_count modes
75wordwrap default width
arraystr_split returns

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

  1. strrev() — String Reverse
  2. str_word_count() — Word Count
  3. wordwrap() — Line Wrapping
  4. chunk_split() — Chunks में तोड़ना
  5. str_split() — Array में Split
  6. Comparison Table
  7. Combined Example
1
strrev() — String को Reverse करना
rev
erse

strrev()

String को उल्टा (reverse) करके return करता है। Palindrome check करना, creative text effects, और interview questions में common।

PHP 4+ Returns: string Interview Favorite
string strrev( string $string )
strrev() — BASIC EXAMPLES
<?php
echo strrev("Hello"); // olleH
echo strrev("PHP"); // PHP (same!)
echo strrev("12345"); // 54321
echo strrev("Hello World"); // dlroW olleH

// Palindrome check — string === reverse?
$words = ["madam", "racecar", "hello", "level"];
foreach ($words as $word) {
  if ($word === strrev($word)) {
    echo "'$word' palindrome है ✅\n";
  } else {
    echo "'$word' palindrome नहीं ❌\n";
  }
}
// 'madam' palindrome है ✅
// 'racecar' palindrome है ✅
// 'hello' palindrome नहीं ❌
// 'level' palindrome है ✅
?>
strrev() — REAL WORLD EXAMPLES
<?php
// 1. Number reverse करना
$num = 12345;
$reversed = (int) strrev((string) $num);
echo $reversed; // 54321

// 2. Case-insensitive palindrome check
$str = "Racecar";
$lower = strtolower($str);
if ($lower === strrev($lower)) {
  echo "Palindrome है!"; // ✅
}

// 3. Token/Code generate करना
$userId = 1042;
$token = strrev(base64_encode($userId));
echo $token; // Simple obfuscation
?>
💡 Interview Tip: "String को बिना strrev() के reverse करो" — यह common interview question है। Answer: for($i = strlen($s)-1; $i >= 0; $i--) echo $s[$i]; — या implode('', array_reverse(str_split($s)));

2
str_word_count() — Words Count करना
word
cnt

str_word_count()

String में कितने words हैं यह count करता है — या words की list/positions return करता है। Blog word count, SEO analysis, content validation में useful।

PHP 5+ Returns: int|array 3 Modes
int|array str_word_count( string $string, int $format = 0, ?string $characters = null )
Format ValueReturn TypeDescription
0 (default)intWords की total count
1arrayWords की indexed list [0=>"Hello", 1=>"World"]
2arrayWords position के साथ [0=>"Hello", 6=>"World"]
str_word_count() — तीनों Modes
<?php
$text = "Hello PHP World Today";

// Mode 0 — count (default)
echo str_word_count($text); // 4
echo str_word_count($text, 0); // 4 (same)

// Mode 1 — words array
print_r(str_word_count($text, 1));
// Array([0]=>"Hello" [1]=>"PHP" [2]=>"World" [3]=>"Today")

// Mode 2 — words with positions
print_r(str_word_count($text, 2));
// Array([0]=>"Hello" [6]=>"PHP" [10]=>"World" [16]=>"Today")
?>
str_word_count() — REAL WORLD EXAMPLES
<?php
// 1. Blog post word count
$article = "PHP is a server-side language used for web development. It is easy to learn.";
$wordCount = str_word_count($article);
$readTime = ceil($wordCount / 200); // 200 words/min average
echo "Words: $wordCount | Read time: ~$readTime min";

// 2. Minimum word validation
$description = trim($_POST['description'] ?? '');
if (str_word_count($description) < 10) {
  echo "❌ Description कम से कम 10 words का होना चाहिए";
}

// 3. Unique words find करना
$sentence = "PHP is great and PHP is easy";
$allWords = str_word_count(strtolower($sentence), 1);
$uniqueWords = array_unique($allWords);
echo "Total: " . count($allWords) . ", Unique: " . count($uniqueWords);
// Total: 7, Unique: 5
?>

3
wordwrap() — Long Text को Wrap करना
wrap
()

wordwrap()

Long string को specified width पर wrap करता है — words तोड़े बिना। Plain text emails, terminal output, और fixed-width displays के लिए।

PHP 4+ Returns: string Email Friendly
string wordwrap( string $string, int $width = 75, string $break = "\n", bool $cut_long_words = false )
ParameterDefaultDescription
$stringWrap करने वाली string
$width75Maximum line width (characters में)
$break"\n"Line break character। HTML के लिए "<br>" use करो
$cut_long_wordsfalsetrue = लंबे words भी cut होंगे
wordwrap() — EXAMPLES
<?php
$text = "PHP is a popular server-side scripting language used for web development. It supports many databases.";

// 30 chars width पर wrap — \n से
echo wordwrap($text, 30, "\n");
// PHP is a popular server-side
// scripting language used for
// web development. It supports
// many databases.

// HTML के लिए <br> use करो
echo wordwrap($text, 40, "<br>", true);

// Long word cut करना
$longWord = "Supercalifragilisticexpialidocious is a word";
echo wordwrap($longWord, 10, "\n", true);
// Supercali
// fragilist
// icexpiali
// docious is
// a word
?>
wordwrap() — REAL WORLD EXAMPLES
<?php
// 1. Plain text email body format करना
$emailBody = "Dear Rahul, Thank you for registering on HindiNotesPoint. We are happy to have you as a member of our learning community.";
$formatted = wordwrap($emailBody, 70, "\r\n"); // Email standard
mail("rahul@gmail.com", "Welcome!", $formatted);

// 2. Blog excerpt wrap करना
$excerpt = "PHP एक open source server side scripting language है जो web development के लिए बनाई गई थी।";
$wrapped = wordwrap($excerpt, 40, "<br>");
echo "<p>$wrapped</p>";

// 3. CLI tool — terminal output
$msg = "Error: Database connection failed. Please check your credentials and try again.";
echo wordwrap($msg, 50, PHP_EOL);
?>
wordwrap() vs nl2br(): wordwrap() automatically line breaks add करता है defined width पर। nl2br() existing \n को <br> में convert करता है। Email के लिए wordwrap, user comments display के लिए nl2br।

4
chunk_split() — String को Chunks में तोड़ना
chk
spl

chunk_split()

String को equal size के chunks में split करके हर chunk के बाद separator insert करता है। Base64 encoding, credit card formatting, और serial numbers के लिए।

PHP 3+ Returns: string Base64 Friendly
string chunk_split( string $string, int $length = 76, string $separator = "\r\n" )
chunk_split() — BASIC EXAMPLES
<?php
// हर 3 chars के बाद dash
echo chunk_split("ABCDEFGHI", 3, "-");
// ABC-DEF-GHI-

// हर 4 chars के बाद space
echo chunk_split("1234567890123456", 4, " ");
// 1234 5678 9012 3456

// Default — 76 chars + \r\n (Base64 email standard)
$b64 = base64_encode(file_get_contents("image.jpg"));
$mime = chunk_split($b64); // Email attachment के लिए
?>
chunk_split() — REAL WORLD EXAMPLES
<?php
// 1. Credit Card display format
$cardNum = "4111111111111234";
$formatted = rtrim(chunk_split($cardNum, 4, "-"), "-");
echo $formatted; // 4111-1111-1111-1234

// 2. License key format — XXXX-XXXX-XXXX-XXXX
$key = strtoupper(substr(md5(uniqid()), 0, 16));
$fKey = rtrim(chunk_split($key, 4, "-"), "-");
echo $fKey; // e.g. A1B2-C3D4-E5F6-G7H8

// 3. IBAN Bank account format
$iban = "IN89370400440532013000";
echo rtrim(chunk_split($iban, 4, " "), " ");
// IN89 3704 0044 0532 0130 00
?>
💡 chunk_split vs wordwrap: chunk_split() हर N characters के बाद separator डालता है — words ignore करता है। wordwrap() word boundaries respect करता है। Numbers/codes के लिए chunk_split, text के लिए wordwrap।

5
str_split() — String को Array में Split करना
str
spl

str_split()

String को characters या fixed-size chunks के array में convert करता है। explode() delimiter से split करता है, str_split() size से। Character-by-character processing के लिए।

PHP 5+ Returns: array explode से अलग
array str_split( string $string, int $length = 1 )
str_split() — BASIC EXAMPLES
<?php
// Default — हर character अलग
print_r(str_split("Hello"));
// Array([0]=>H [1]=>e [2]=>l [3]=>l [4]=>o)

// Length 2 — हर 2 chars एक chunk
print_r(str_split("Hello", 2));
// Array([0]=>He [1]=>ll [2]=>o)

// Length 3
print_r(str_split("ABCDEFGHI", 3));
// Array([0]=>ABC [1]=>DEF [2]=>GHI)
?>
str_split() — REAL WORLD EXAMPLES
<?php
// 1. String reverse — str_split + array_reverse
$str = "Hello";
$reversed = implode("", array_reverse(str_split($str)));
echo $reversed; // olleH (strrev के बिना!)

// 2. Character frequency count
$text = "banana";
$chars = str_split($text);
$freq = array_count_values($chars);
print_r($freq);
// Array([b]=>1 [a]=>3 [n]=>2)

// 3. Phone number format करना
$phone = "9876543210";
$chunks = str_split($phone, 5);
echo implode("-", $chunks); // 98765-43210

// 4. String को shuffle करना
$letters = str_split("abcdefghij");
shuffle($letters);
echo implode("", $letters); // Random order

// 5. Password strength check — unique chars
$pass = "P@ssw0rd";
$uniqueChars = count(array_unique(str_split($pass)));
echo "Unique characters: $uniqueChars"; // 8
?>

✅ str_split() — size से split

// Fixed size chunks
str_split("Hello", 2);
// ["He","ll","o"]

// Character by character
str_split("abc");
// ["a","b","c"]

ℹ️ explode() — delimiter से split

// Delimiter से split
explode(",", "a,b,c");
// ["a","b","c"]

// Words split करना
explode(" ", "Hi PHP");
// ["Hi","PHP"]

6
Comparison — पाँचों Functions एक नज़र में
FunctionInput → OutputReturnsBest Use
strrev()"Hello" → "olleH"stringPalindrome check, reverse text
str_word_count()"Hi PHP World" → 3int|arrayBlog word count, SEO analysis
wordwrap()Long text → 40 char linesstringEmail body, terminal output
chunk_split()"1234567890" → "1234-5678-90"stringCredit card, license key format
str_split()"Hello" → ["H","e","l","l","o"]arrayChar processing, shuffle, frequency

7
Combined Example — Text Analysis Tool
COMBINED — Blog Post Analyzer
<?php
$post = "PHP is a popular open source scripting language. It is widely used for web development and supports many databases including MySQL.";

// 1. str_word_count — words count
$wordCount = str_word_count($post); // 23
$readTime = ceil($wordCount / 200); // 1 min

// 2. str_split — character frequency
$chars = str_split(strtolower($post));
$freq = array_count_values($chars);
arsort($freq);
$topChar = array_key_first($freq); // most used char

// 3. strrev — palindrome check करना
$words = str_word_count(strtolower($post), 1);
$palindromes = array_filter($words, fn($w) => $w === strrev($w) && strlen($w) > 1);

// 4. wordwrap — 60 char excerpt
$excerpt = wordwrap(substr($post, 0, 80), 40, "<br>");

// Display
echo "Words: $wordCount | Read time: ~$readTime min\n";
echo "Most used char: '$topChar' ({$freq[$topChar]} times)\n";
echo "Palindromes: " . implode(", ", $palindromes) . "\n";
echo "Excerpt: <p>$excerpt</p>";
?>
Pattern: str_word_count (count) → str_split (char analysis) → strrev (palindrome) → wordwrap (display)

निष्कर्ष

यह पाँच functions text transformation के लिए हैं — reverse, count, wrap, chunk, split। इन्हें array functions के साथ combine करने पर बहुत powerful text processing होती है।

strrev() — palindrome check। Numbers reverse के लिए (int)strrev((string)$num।

str_word_count() — mode 0 = count, 1 = words array, 2 = positions।

wordwrap() — email body के लिए 70 chars। HTML के लिए "<br>" pass करो।

chunk_split() — card numbers, license keys। rtrim() से trailing separator हटाओ।

str_split() — character processing। shuffle/frequency count के लिए array functions के साथ।

🚀 अगला: Chapter 7.5 — htmlspecialchars, strip_tags, addslashes, md5, sha1 — Security & Hashing functions।