PHP Strings · Chapter 7.2 · Search & Manipulation

PHP String Functions
strpos · str_contains · str_replace · substr · explode

पाँच सबसे powerful PHP String Functions — String ढूँढना, Replace करना, काटना, और तोड़ना। Syntax, Parameters, Real World Examples, और Common Mistakes।

🔍 strpos() ✅ str_contains() 🔄 str_replace() ✂️ substr() 💥 explode()
5Functions इस chapter में
PHP 8str_contains available
0Index शुरू होता है
falsestrpos — not found

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

  1. strpos() — Position ढूँढना
  2. str_contains() — Contains Check
  3. str_replace() — Replace करना
  4. substr() — हिस्सा निकालना
  5. explode() — Array में तोड़ना
  6. Comparison Table
  7. Combined Real World Example
1
strpos() — String में Position ढूँढना
str
pos

strpos()

String में किसी substring की पहली occurrence की position (index) return करता है। नहीं मिले तो false return करता है।

PHP 4+ Returns: int|false Case Sensitive
int|false strpos( string $haystack, string $needle, int $offset = 0 )
ParameterTypeज़रूरी?Description
$haystackstringRequiredवो string जिसमें ढूँढना है (भूसे का ढेर)
$needlestringRequiredजो ढूँढना है (सुई)
$offsetintOptionalकिस position से search शुरू करें। Default: 0
Returnint|falseमिली तो position (0 से), नहीं मिली तो false
strpos() — BASIC EXAMPLES
<?php
$str = "Hello PHP World";
// 0123456789...

echo strpos($str, "PHP"); // 6 (P की position)
echo strpos($str, "World"); // 10
echo strpos($str, "Hello"); // 0 (पहली position!)
echo strpos($str, "Java"); // false (नहीं मिला)

// Case Sensitive — php !== PHP
echo strpos($str, "php"); // false (lowercase नहीं मिलेगा)
echo stripos($str, "php"); // 6 (stripos = case insensitive)

// Offset — किस position से search शुरू करें
$str2 = "cat and cat and cat";
echo strpos($str2, "cat"); // 0 (पहली)
echo strpos($str2, "cat", 1); // 8 (दूसरी)
echo strpos($str2, "cat", 9); // 16 (तीसरी)
?>
⚠️ सबसे बड़ा Trap — position 0 = false नहीं!
अगर substring string की शुरुआत में मिले तो position 0 return होती है। PHP में if (0) false होता है! इसलिए:

if (strpos($str, "Hello")) // ❌ WRONG — position 0 को miss करेगा
if (strpos($str, "Hello") !== false) // ✅ CORRECT
strpos() — REAL WORLD EXAMPLES
<?php
// 1. Email में @ है या नहीं
$email = "rahul@gmail.com";
if (strpos($email, "@") !== false) {
  echo "✅ Email valid लग रहा है";
}

// 2. URL में protocol check
$url = "https://hindinotespoint.com";
if (strpos($url, "https") === 0) {
  echo "✅ Secure HTTPS URL";
}

// 3. @ से पहले username निकालना
$pos = strpos($email, "@");
$username = substr($email, 0, $pos);
echo $username; // rahul

// 4. Spam word check
$comment = "Buy cheap medicine now!";
$spamWords = ["cheap", "buy now", "free money"];
foreach ($spamWords as $word) {
  if (stripos($comment, $word) !== false) {
    echo "❌ Spam detected: " . $word;
  }
}
?>
💡 strpos vs stripos: strpos() case-sensitive है। stripos() case-insensitive है (i = insensitive)। User input search में stripos better है।

2
str_contains() — String में है या नहीं (PHP 8)
str
has?

str_contains()

PHP 8 में आया सबसे clean function — check करता है कि string में कोई substring है या नहीं। true/false return करता है। strpos का modern replacement।

PHP 8.0+ Returns: bool Case Sensitive Recommended
bool str_contains( string $haystack, string $needle )

✅ PHP 8 — str_contains (Clean!)

if (str_contains($email, "@")) {
  echo "Valid!";
}

// Simple, readable, no trap!

⚠️ PHP 7 — strpos (Tricky)

if (strpos($email, "@") !== false) {
  echo "Valid!";
}

// !== false लिखना ज़रूरी — mistake prone
str_contains() — EXAMPLES
<?php
$str = "Hello PHP World";

var_dump(str_contains($str, "PHP")); // bool(true)
var_dump(str_contains($str, "Java")); // bool(false)
var_dump(str_contains($str, "php")); // bool(false) — case sensitive
var_dump(str_contains($str, "")); // bool(true) — empty string always true
?>
str_contains() + str_starts_with() + str_ends_with() — PHP 8 Trio
<?php
$url = "https://hindinotespoint.com/php/strings";
$file = "profile_photo.jpg";

// str_contains — कहीं भी है?
if (str_contains($url, "hindinotespoint")) {
  echo "✅ Internal link है";
}

// str_starts_with — शुरू में है?
if (str_starts_with($url, "https")) {
  echo "✅ Secure URL";
}

// str_ends_with — अंत में है?
if (str_ends_with($file, ".jpg")) {
  echo "✅ Valid image file";
}

// Multiple extensions check
$allowed = ['.jpg', '.jpeg', '.png', '.gif'];
$isValid = false;
foreach ($allowed as $ext) {
  if (str_ends_with(strtolower($file), $ext)) {
    $isValid = true;
    break;
  }
}
echo $isValid ? "✅ Valid image" : "❌ Invalid file";
?>
✅ PHP 8+ projects में: strpos की जगह str_contains use करो। Code readable होता है, !== false का झंझट नहीं, bugs कम। PHP 7 support चाहिए तो strpos + !== false।

3
str_replace() — String में Replace करना
str
rpl

str_replace()

String में किसी word या character को ढूँढकर उसे दूसरे से replace करता है। Content filtering, template filling, URL slug — बहुत versatile function है।

PHP 4+ Returns: string|array Case Sensitive
string|array str_replace( $search, $replace, $subject, &$count = null )
ParameterTypeज़रूरी?Description
$searchstring|arrayRequiredजो ढूँढना है — string या array of strings
$replacestring|arrayRequiredजिससे replace करना है
$subjectstring|arrayRequiredजिस string में replace करना है
&$countintOptionalकितनी बार replace हुआ — by reference
str_replace() — BASIC से ADVANCED
<?php
// Basic replace
echo str_replace("World", "PHP", "Hello World");
// Hello PHP

// Case insensitive — str_ireplace
echo str_ireplace("WORLD", "PHP", "Hello World");
// Hello PHP (WORLD को भी match करेगा)

// Array से multiple replace एक साथ
$search = ["Delhi", "Mumbai", "Chennai"];
$replace = ["New Delhi", "Mumbai City", "Madras"];
$text = "Delhi और Mumbai बड़े शहर हैं";
echo str_replace($search, $replace, $text);
// New Delhi और Mumbai City बड़े शहर हैं

// Replace delete — empty string से replace
$dirty = "Hello<script>alert('xss')</script> World";
echo str_replace(["<script>", "</script>"], "", $dirty);
// Hello alert('xss') World

// $count — कितनी बार replace हुआ
$count = 0;
str_replace("a", "@", "banana", $count);
echo $count; // 3
?>
str_replace() — REAL WORLD EXAMPLES
<?php
// 1. URL-friendly slug बनाना
$title = "PHP Tutorial in Hindi 2025";
$slug = strtolower(str_replace(" ", "-", trim($title)));
echo $slug; // php-tutorial-in-hindi-2025

// 2. Email template — placeholder replace
$template = "Dear {NAME}, आपका order {ORDER_ID} ship हो गया।";
$email = str_replace(
  ['{NAME}', '{ORDER_ID}'],
  ['Rahul', 'ORD-2025-001'],
  $template
);
echo $email;
// Dear Rahul, आपका order ORD-2025-001 ship हो गया।

// 3. Phone number format करना
$phone = "98-765-43210";
$clean = str_replace(["-", " ", "(", ")"], "", $phone);
echo $clean; // 9876543210
?>
💡 Template Pattern: Email, SMS, notifications में placeholder pattern ({NAME}, {{email}}) बनाओ और str_replace से fill करो — यह professional approach है।

4
substr() — String का हिस्सा निकालना
sub
str

substr()

String का कोई specific हिस्सा (substring) निकालता है — start position और length बताओ। Blog preview, credit card masking, file extension — हर जगह use।

PHP 4+ Returns: string 0-indexed
string substr( string $string, int $offset, ?int $length = null )
ParameterTypeज़रूरी?Description
$stringstringRequiredOriginal string
$offsetintRequiredStart position। Negative = अंत से count करो
$lengthint|nullOptionalकितने characters चाहिए। null = end तक
substr() — VISUAL GUIDE
<?php
$str = "HindiNotes";
// H i n d i N o t e s
// 0 1 2 3 4 5 6 7 8 9 (forward)
// -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 (backward)

echo substr($str, 0, 5); // Hindi (0 से 5 chars)
echo substr($str, 5); // Notes (5 से end तक)
echo substr($str, 5, 3); // Not (5 से 3 chars)
echo substr($str, -5); // Notes (आखिरी 5 chars)
echo substr($str, -5, 3); // Not (आखिरी 5 से 3 chars)
echo substr($str, 2, -2); // ndiNot (2 से, आखिरी 2 छोड़ो)
?>
📰
Blog Preview

150 chars + "..." truncate

💳
Card Masking

XXXX-XXXX-XXXX-1234

📧
Email Username

@ से पहले का हिस्सा

📁
File Extension

.jpg, .php निकालना

substr() — REAL WORLD EXAMPLES
<?php
// 1. Blog content preview
$content = "PHP एक बहुत powerful server-side language है जो web development के लिए use होती है।";
$preview = strlen($content) > 40
  ? substr($content, 0, 40) . "..."
  : $content;
echo $preview;

// 2. Credit card masking
$card = "4111111111111234";
$last4 = substr($card, -4);
$masked = "XXXX-XXXX-XXXX-" . $last4;
echo $masked; // XXXX-XXXX-XXXX-1234

// 3. File extension निकालना
$file = "document.pdf";
$dotPos = strrpos($file, ".");
$extension = substr($file, $dotPos + 1);
echo $extension; // pdf

// 4. Name initials बनाना
$first = "Rahul";
$last = "Kumar";
$initials = substr($first, 0, 1) . substr($last, 0, 1);
echo strtoupper($initials); // RK
?>
strrpos() vs strpos(): File extension निकालने के लिए strrpos() use करो — यह last occurrence ढूँढता है। "photo.backup.jpg" में strpos(".") → 5 लेकिन strrpos(".") → 13 (सही extension)।

5
explode() — String को Array में तोड़ना
exp
lode

explode()

String को किसी delimiter (separator) से split करके array बनाता है। CSV data, tags, URL paths, comma-separated values — हर जगह काम आता है।

PHP 4+ Returns: array Pair: implode()
array explode( string $separator, string $string, int $limit = PHP_INT_MAX )
ParameterTypeज़रूरी?Description
$separatorstringRequiredजिससे split करना है — जैसे ",", " ", "|", "-"
$stringstringRequiredजो string तोड़नी है
$limitintOptionalMax कितने pieces चाहिए। Negative = last N छोड़ो
explode() — BASIC EXAMPLES
<?php
// Comma से split
$fruits = explode(",", "Apple,Mango,Banana,Orange");
print_r($fruits);
// Array ( [0] => Apple [1] => Mango [2] => Banana [3] => Orange )

// Space से split
$words = explode(" ", "Hello PHP World");
echo $words[0]; // Hello
echo $words[1]; // PHP
echo $words[2]; // World

// $limit — max 2 pieces चाहिए
$parts = explode(",", "a,b,c,d,e", 3);
print_r($parts);
// Array ( [0] => a [1] => b [2] => c,d,e )
?>
explode() — REAL WORLD EXAMPLES
<?php
// 1. CSV data process करना
$csvLine = "Rahul,25,Delhi,Developer";
$data = explode(",", $csvLine);
echo "नाम: " . $data[0]; // Rahul
echo "उम्र: " . $data[1]; // 25
echo "शहर: " . $data[2]; // Delhi
echo "काम: " . $data[3]; // Developer

// 2. Date split करना
$date = "2025-12-25";
[$year, $month, $day] = explode("-", $date); // Destructuring
echo "Year: $year, Month: $month, Day: $day";

// 3. Tags process करना
$tagStr = "PHP, Laravel, MySQL, HTML, CSS";
$tags = explode(", ", $tagStr);
foreach ($tags as $tag) {
  echo "<span class='tag'>" . trim($tag) . "</span>";
}

// 4. URL path segments
$path = "php/strings/functions";
$segments = explode("/", $path);
echo "Section: " . $segments[0]; // php
echo "Page: " . $segments[2]; // functions

// 5. implode — वापस जोड़ना (explode का opposite)
$joined = implode(" | ", $tags);
echo $joined; // PHP | Laravel | MySQL | HTML | CSS
?>
💡 Modern PHP Trick: PHP 7.1+ में array destructuring से explode और भी clean लगता है: [$year, $month, $day] = explode("-", $date); — तीन variables एक line में!

6
Comparison — पाँचों Functions एक नज़र में
FunctionInputOutputReturnsBest Use
strpos()"Hello PHP", "PHP"6int|falsePosition चाहिए — substr के साथ use
str_contains()"Hello PHP", "PHP"trueboolसिर्फ है/नहीं — PHP 8 preferred
str_replace()"Hi World", "World", "PHP""Hi PHP"stringReplace, slug, template filling
substr()"HelloPHP", 5, 3"PHP"stringMasking, preview, extension
explode()",", "a,b,c"[a,b,c]arrayCSV, tags, date, URL parse

7
Combined Example — Blog Post Processing
यह देखो कि एक Blog Post create करते समय सभी 5 functions एक साथ कैसे use होते हैं:
COMBINED — Blog Post Create करना
<?php
// Raw user input
$rawTitle = " How To Learn PHP in 2025 ";
$rawContent = "PHP एक popular language है। यह web development के लिए बहुत अच्छी है। इसे सीखना easy है।";
$rawTags = "PHP, Web Development, Tutorial, Hindi, Beginner";

// Step 1: Title clean करो (trim से)
$title = trim($rawTitle); // "How To Learn PHP in 2025"

// Step 2: URL slug बनाओ (str_replace से)
$slug = strtolower(str_replace(" ", "-", $title));
// "how-to-learn-php-in-2025"

// Step 3: Content preview बनाओ (substr से)
$preview = substr($rawContent, 0, 50) . "...";
// "PHP एक popular language है। यह web developm..."

// Step 4: Tags array बनाओ (explode से)
$tagsArr = explode(", ", $rawTags);
// ["PHP", "Web Development", "Tutorial", "Hindi", "Beginner"]

// Step 5: "PHP" tag है या नहीं check करो
if (str_contains($rawTags, "PHP")) {
  echo "✅ PHP category में add होगा";
}

// Step 6: Tags में "Tutorial" की position ढूँढो
$tutPos = array_search("Tutorial", $tagsArr);
echo "Tutorial tag index: " . $tutPos; // 2

// Step 7: Display
echo "Title: $title";
echo "Slug: $slug";
echo "Preview: $preview";
echo "Tags: " . implode(" | ", $tagsArr);
?>
Real pattern: trim → str_replace (slug) → substr (preview) → explode (tags) → str_contains (category check) — यही flow हर blog/CMS में होता है।

निष्कर्ष (Conclusion)

Chapter 7.1 और 7.2 मिलकर PHP String Functions का complete toolkit हैं। 10 functions जो हर PHP project में daily use होते हैं — इन्हें याद कर लो और practice करो।

strpos() — position चाहिए। हमेशा !== false use करो।

str_contains() — PHP 8 का clean way। true/false simple।

str_replace() — replace, slug, template — बहुत versatile।

substr() — negative index भी काम करता है — आखिरी N characters।

explode() — string को array में। implode() से वापस जोड़ो।

🚀 अगला Sub-Chapter: Chapter 7.3 में sprintf, number_format, str_pad, str_repeat, nl2br — Formatting और Utility functions सीखें।