Strings are very common in PHP, so it's vital to learn how to handle them effectively. Fortunately, PHP provides many functions for dealing with Strings. Once you understand the purpose of a few PHP functions, you can easily handle a variety of Strings, from simple to complex.

Common String Handling Functions:

1. strlen()

The strlen() function is used to return the length of a String.

echo strlen("Hello world!"); //  Output: 12

2. str_word_count()

The str_word_count() function is used to count the number of words in a String.

echo str_word_count("Hello world!"); //  Output: 2

3. strrev()

The strrev() function is used to reverse a String.

echo strrev("Hello world!"); //  Output: !dlrow olleH

4. strpos()

The strpos() function is used to search for a specific text within a String. If a match is found, it returns the position of the first character of the match. If no match is found, it returns FALSE.

// Search for the text "world" in the String "Hello world!":
echo strpos("Hello world!", "world"); // Output: 6

Note: The first character's position in a string is 0 (not 1).

5. str_replace()

The str_replace() function is used to replace some characters with some other characters in a string.

// Thay thế "world" thành "Dolly"
echo str_replace("world", "Dolly", "Hello world!"); // Output:  Hello Dolly!

There are many more functions for handling Strings, refer more here: STRING HANDLING FUNCTION DOCUMENTATION

Ngọc Phương

Web Developer

Thank you for visiting my blog. My name is Phuong and I have more than 10 years of experience in website development. I am confident in asserting myself as an expert in creating impressive and effective websites. Anyone in need of website design can contact me via Zalo at 0935040740.

0 feedback