Manipulating the string as an array in PHP

 Manipulating the string as an array in PHP

In PHP, you can treat strings as arrays and manipulate them using various functions and array-like operations.

 Examples:-  Manipulating strings as arrays:

  Example 1: Accessing Characters

<?php

$string = "Hello, World!";

$length = strlen($string);

 

// Access each character individually

for ($i = 0; $i < $length; $i++) {

    echo $string[$i] . " ";

}

?>

// Output: H e l l o ,   W o r l d !

 

  Example 2: Exploding a String into an Array

 <?php

$string = "apple,orange,banana";

$fruits = explode(",", $string);

 

// $fruits is now an array

print_r($fruits);

?>

// Output: Array ( [0] => apple [1] => orange [2] => banana )

  

 Example 3: Joining Array Elements into a String

 <?php

$fruits = array("apple", "orange", "banana");

$string = implode(", ", $fruits);

 // $string is now a string

echo $string;

?>

// Output: apple, orange, banana

 

 Example 4: Substring

 <?php

$string = "Hello, World!";

 // Get a substring

$substring = substr($string, 0, 5);

?>

// Output: Hello

 

 Example 5: Replacing Substring

 <?php

$string = "Hello, World!";

 // Replace a substring

$newString = str_replace("World", "PHP", $string);

?>

// Output: Hello, PHP!

 

 Example 6: Case Conversion

 <?php

$string = "Hello, World!";

 // Convert to lowercase

$lowercase = strtolower($string);

 // Convert to uppercase

$uppercase = strtoupper($string);

?>

// Output: hello, world! / HELLO, WORLD!

  

 Example 7: Checking if a String Contains a Substring

 <?php

$string = "Hello, World!";

 // Check if the string contains "World"

if (strpos($string, "World") !== false) {

    echo "Contains 'World'";

} else {

    echo "Does not contain 'World'";

}

?>

// Output: Contains 'World'

 

  Example 8: Counting Words in a String

 <?php

$string = "The quick brown fox";

 // Count words in a string

$wordCount = str_word_count($string);

?>

// Output: 4

 

 Example 9: Checking if a String Starts or Ends with a Substring

 <?php

$string = "Hello, World!";

 // Check if the string starts with "Hello"

if (strncmp($string, "Hello", 5) === 0) {

    echo "Starts with 'Hello'";

} else {

    echo "Does not start with 'Hello'";

}

?>

// Output: Starts with 'Hello'

  

<?php

// Check if the string ends with "World!"

if (substr_compare($string, "World!", -6) === 0) {

    echo "Ends with 'World!'";

} else {

    echo "Does not end with 'World!'";

}

?>

// Output: Ends with 'World!'

 

  Example 10: Reversing a String

 <?php

$string = "Hello, World!";

 // Reverse a string

$reversedString = strrev($string);

?>

// Output: !dlroW ,olleH

  

 Example 11: Counting Characters in a String

 <?php

$string = "Hello, World!";

// Count characters in a string

$charCount = count_chars($string, 1);

?>

// Output: Array ( [32] => 1 [33] => 1 [44] => 1 [72] => 1 [87] => 1 [100] => 1 [101] => 1 [108] => 3 [111] => 2 [114] => 2 )

 

 Example 12: Padding a String

 <?php

$string = "Hello";

 // Pad a string to a certain length with spaces

$paddedString = str_pad($string, 10);

?>

// Output: Hello     (padded with spaces to a length of 10)

  

 Example 13: Trimming Characters from the Beginning or End

 <?php

$string = "   Hello, World!   ";

 // Trim spaces from the beginning and end

$trimmedString = trim($string);

?>

// Output: Hello, World!

  

 Example 14: Converting a String to an Array of Characters

 <?php

$string = "Hello, World!";

 // Convert a string to an array of characters

$charArray = str_split($string);

 // $charArray is now an array

print_r($charArray);

?>

// Output: Array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => , [6] =>   [7] => W [8] => o [9] => r [10] => l [11] => d [12] => ! )

  

 Example 15: Finding the Last Occurrence of a Substring

 <?php

$string = "Hello, World! Hello, PHP!";

 // Find the last occurrence of "Hello"

$lastHelloPosition = strrpos($string, "Hello");

?>

// Output: 13 (position of the last occurrence of "Hello")

 

 Example 16: Case-Insensitive String Comparison

 <?php

$string1 = "Hello, World!";

$string2 = "hello, world!";

// Case-insensitive string comparison

if (strcasecmp($string1, $string2) === 0) {

    echo "Strings are equal (case-insensitive)";

} else {

    echo "Strings are not equal (case-insensitive)";

}

?>

// Output: Strings are equal (case-insensitive)

  

 Example 17: Replacing Only the First Occurrence

 <?php

$string = "apple, orange, banana, orange, cherry";

 // Replace the first occurrence of "orange"

$newString = preg_replace('/orange/', 'grape', $string, 1);

?>

// Output: apple, grape, banana, orange, cherry

  

 Example 18: Extracting a Portion of the String

 <?php

$string = "The quick brown fox jumps over the lazy dog";

 // Extract a portion of the string

$portion = substr($string, 10, 15);

?>

// Output: brown fox jumps

 

 Example 19: Converting a String to an Array of Words

 <?php

$string = "The quick brown fox";

 // Convert a string to an array of words

$wordArray = explode(" ", $string);

 // $wordArray is now an array

print_r($wordArray);

?>

// Output: Array ( [0] => The [1] => quick [2] => brown [3] => fox )

  

 Example 20: Using Regular Expressions to Match Patterns

<?php

$string = "The price is $15.99";

 // Extract the price using a regular expression

preg_match('/\$([0-9.]+)/', $string, $matches);

// $matches contains the matched values

print_r($matches);

?>

// Output: Array ( [0] => $15.99 [1] => 15.99 )

 

 Example 21: Shuffling Characters in a String

 <?php

$string = "Hello, World!";

 // Convert the string to an array, shuffle, and then implode

$shuffledString = implode("", str_shuffle($string));

?>

// Output: random order of characters from the original string

 

 Example 22: Finding the Difference Between Two Strings

 <?php

$string1 = "Hello, World!";

$string2 = "Hello, PHP!";

 // Find the difference between two strings

$difference = strspn($string1 ^ $string2, "\0");

?>

// Output: 7 (number of common initial characters)

  

 Example 23: Converting a String to Title Case

<?php

$string = "the quick brown fox";

 // Convert the string to title case

$titleCaseString = ucwords($string);

?>

// Output: The Quick Brown Fox

  

 Example 24: Swapping Case of Characters

 <?php

$string = "Hello, World!";

 // Swap the case of characters

$swappedCaseString = strtr($string, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');

?>

// Output: hELLO, wORLD!

  

 Example 25: Counting Occurrences of a Substring

 <?php

$string = "apple, orange, banana, orange, cherry";

 // Count occurrences of "orange"

$occurrences = substr_count($string, "orange");

?>

// Output: 2

  

 Example 26: Removing HTML and PHP Tags

 <?php

$htmlString = "<p>Hello, <b>World!</b></p>";

 // Remove HTML and PHP tags

$plainTextString = strip_tags($htmlString);

?>

// Output: Hello, World!

 

 Example 27: Repeating a String Multiple Times

 <?php

$string = "Hello";

 // Repeat the string multiple times

$repeatedString = str_repeat($string, 3);

?>

// Output: HelloHelloHello

  

These examples showcase additional ways to manipulate strings as arrays in PHP, covering a range of tasks from shuffling characters to counting occurrences and formatting. Always refer to the [PHP manual](https://www.php.net/manual/en/ref.strings.php) for more details and additional string manipulation functions.

Post a Comment

0 Comments