Web programming

Working with String Data Type in PHP

Ngoc Phuong

Ngoc Phuong

25-02-2021 . 61 view

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

Ngoc Phuong
Ngoc Phuong

Web Developer

Thank you for visiting my website. My name is Ngoc Phuong, and I have over 10 years of experience in website development. I am confident in stating that I am an expert in creating impressive and effective websites. If you need a website designed, please feel free to contact me via email at [email protected].

0 feedback