Table of Contents
Examples of String Functions in PHP
1. Addcslashes()
2. Addslashes()
3. bin2hex()
4. chop()
5. chr()
6. chunk_split()
7. convert_uudecode()
8. count_chars()
9. crc32()
10. Implode()
11. htmlspecialchars()
12. ltrim()
13. number_format()
14. print()
15. md5()
16. strtok()
17. strupper()
18. substr()
19. substr_replace()
20. wordwrap()
21. Strlen()
22. Strrev()
23. Strpos()
24. Str_repeat()
25. Str_replace()
26. Nl2br()
27. similar_text()
28. sprintf()
29. Str_ireplace()
30. str_shuffle()
31. str_word_count()
32. Strcspn()
33. str_pad()
34. Ord()
35. Strchr()
36. Strspn()
Home Backend Development PHP Tutorial PHP String Functions

PHP String Functions

Aug 29, 2024 pm 12:46 PM
php

PHP inbuilt supports a few data types. Apart from these, PHP also supports many functions that are used while working on some data. PHP String functions are some of those functions that are used to manipulate string data. All these functions are predefined. There is a need for installing any plugins. Let’s look at some of the PHP string functions.

ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Below are some of the string functions, and examples are illustrated with the following syntax.

<?php
echo func( "<data>" );
?>
Copy after login

Examples of String Functions in PHP

The string function is easy to use. Here we will discuss how to use string function in PHP programming with the help of examples.

1. Addcslashes()

This returns a string with backslashes in front of specific characters

E.g.:

echo addcslashes ("Hello World!","W");
Copy after login

Output:

Hellow World

2. Addslashes()

This returns string with backslashes in front of predefined characters

E.g.:

echo addcslashes('Hello "World" you');
Copy after login

Output:

Hello ” World” you.

3. bin2hex()

Converts binary data into hexadecimal data

E.g.:

echo bin2hex ("Hello");
Copy after login

Output:

48656c6c6f

4. chop()

Removes whitespaces or any predefined characters from the right end if specified

E.g.:

echo chop ("WelcomeBack" , "Back");
Copy after login

Output:

Welcome

5. chr()

This PHP string function returns the character of a specified ASCII value.

E.g.:

echo char(52);
Copy after login

Output:

4

6. chunk_split()

Used to split a string into smaller parts

E.g.:

echo chunk_split ($str, 2,", ");
Copy after login

Output:

We,lc,om,e,

7. convert_uudecode()

This decodes a uuencoded string

E.g.:

echo convert_uudecode ("+22!L;W9E( %!( 4\"$`\n` ");
Copy after login

Output:

I love PHP!

convert_uuencode() does the reverse of convert_uudecode()

8. count_chars()

This PHP string function outputs the data about the number of characters in a string.

E.g.:

echo count_chars ("Hello", 3);
Copy after login

Output:

Helo

Note: The integer value is the mode which is used to specify the type of output required
  • 0 – an array with the byte-value as key and the frequency of every byte as value.
  • 1 – same as 0, but only byte-values with a frequency greater than zero are listed.
  • 2 – same as 0, but only byte-values with a frequency equal to zero are listed.
  • 3 – a string containing all unique characters is returned.
  • 4 – a string containing all not used characters is returned.

9. crc32()

This calculates the 32-bit cyclic redundancy checksum( A Mathematical function) of a string.

E.g.:

crc32 ("Hello World!");
Copy after login

Output:

472456355

10. Implode()

This joins the array elements with a specified string

E.g.:

$array = array ('lastname', 'email', 'phone');
echo implode(",", $array);
Copy after login

Output:

lastname, email, phone

Note: join() also does the same. It is the alias of implode().

11. htmlspecialchars()

This converts some predefined characters to HTML entities, i.e. it shows the source.

Eg:

$str = "I am <b>Bold</b>";
echo $str; => I am <strong>Bold</strong>
echo htmlspecialchars($str);
Copy after login

Output:

I am Bold

12. ltrim()

This PHP string function removes white spaces or predefined characters from the left of the string.

E.g.:

echo ltrim ("Just a sample", "Just");
Copy after login

Output:

a sample

Note: rtrim() does a similar job from right
trim() does the same from both ends.

13. number_format()

This formats the number with grouped thousands

E.g.:

echo number_format (1000000);
Copy after login

Output:

1,000,000

14. print()

This simply outputs the string and is slower than the echo

Also, the print should not be used with ()

E.g.:

print "Hello";
Copy after login

Output:

Hello

15. md5()

This calculates the md5 hash of the string

E.g.:

echo md5 ("Hello");
Copy after login

Output:

8b1a9953c4611296a827abf8c47804d7

16. strtok()

This splits a string into smaller strings

E.g.:

$string = "This is to break a string";
$token = strtok ($string, " ");
echo($token); => This
To get all words of string,
while ($token !== false){
echo "$token<br>";
$token = strtok(" ");
}
Copy after login

Output:

This
is
to
break
string

17. strupper()

This converts a string to uppercase characters

E.g.:

echo strupper ("Beautiful Day");
Copy after login

Output:

BEAUTIFUL DAY

Note: strlower() converts strings to all lowercase characters.

18. substr()

This returns part of the string starting with the index specified

E.g.:

echo subst ("A Hot Day", 3);
Copy after login

Output:

ot Day

19. substr_replace()

This PHP string function replaces a part of the string with the string specified.

E.g.:

echo substr_replace ("Hot", "Day",0);
Copy after login

Output:

Day

20. wordwrap()

This wraps a string to a number of characters

E.g.:

echo wordwrap ("Hello World", 5, "\n");
Copy after login

Output:

Hello
World

21. Strlen()

This is used to determine the length of the string passed

E.g.:

echo strlen ("Hello");
Copy after login

Output:

5

22. Strrev()

This PHP string function is used to get the reverse of the string

E.g.:

echo strrev ("welcome");
Copy after login

Output:

emoclew

23. Strpos()

This returns the position of the first occurrence of a string inside a string

E.g.:

echo strops("There you go", "go");
Copy after login

Output:

11

24. Str_repeat()

This repeats a string specified number of times

E.g.:

echo str_repeat ('b', 5);
Copy after login

Output:

bbbbb

25. Str_replace()

This PHP string function finds the specified word, replaces that with a specified word, and return the string

E.g.:

echo str_replace ("great", "wonderful", "have a great day");
Copy after login

Output:

have a wonderful day

26. Nl2br()

This PHP string function inserts html line breaks in front of each new line of the string

E.g.:

echo nl2br ("Lets break \nthe sentence");
Copy after login

Output:

Lets break

the sentence

27. similar_text()

This calculates the similarity between two strings

E.g.:

echo similar_text ("Hello World","Great World");
Copy after login

Output:

7

28. sprintf()

This PHP string function writes a formatted string to a variable

E.g.:

echo sprintf ("There are %u wonders in the World",7);
Copy after login

Output:

There are 7 wonders in the World

29. Str_ireplace()

This replaces characters in the string with specific characters. This function is case insensitive.

E.g.:

echo str_ireplace ("great", "WOW", "This is a great place");
Copy after login

Output:

This is a wow place

30. str_shuffle()

This randomly shuffles all characters in a string

E.g.:

echo str_shuffle("Hello World");
Copy after login

Output:

lloeWlHdro

31. str_word_count()

This PHP string function returns the number of words in the given string

E.g.:

echo str_word_count ("a nice day");
Copy after login

Output:

3

32. Strcspn()

This returns the number of characters before the specified character

echo strcspn ("Hello world!","w");
Copy after login

Output:

6

33. str_pad()

This function is used to pad to the right side of the string, a specified number of characters with the specified character

E.g.:

echo str_pad ("Hello", 10, ".");
Copy after login

Output:

Hello…..

34. Ord()

This PHP string function returns the ASCII value of the first character of the string.

E.g.:

echo ord ("hello");
Copy after login

Output:

104

35. Strchr()

Find the first occurrence of a specified string within a string

E.g.:

echo strchr ("Hello world!", "world");
Copy after login

Output:

world!

36. Strspn()

This returns the number of characters found in the string that contains characters from the specified string.

E.g.:

echo strspn ("Hello world!", "Hl");
Copy after login

Output:

1

There are few more string functions available in PHP. The above string functions are commonly used functions in PHP for various requirements.

The above is the detailed content of PHP String Functions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1242
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles