PHP String Functions

PHP String Functions

In this article, we’ll explore PHP String Functions

Strings are an integral part of almost every web application, and PHP provides a rich collection of built-in PHP string functions that empower developers to manipulate and process text data efficiently. Whether you’re a beginner or an experienced PHP developer, understanding the array of PHP string functions available can significantly enhance your coding capabilities.

We’ll embark on a journey through the realm of PHP string functions, exploring their features, use cases, and best practices to help you harness their full potential.

PHP String Functions

A string function is a function that can be used to manipulate and process strings. PHP String functions are used to perform tasks such as:

  • Converting strings to different formats
  • Searching and replacing text
  • Splitting and joining strings
  • Validating and sanitizing strings

The followings are useful php string functions:

1. Strlen

PHP has a predefined function to get the length of a string. Strlen() displays the length of any string. It is more commonly used in validating input fields where the user is limited to enter a fixed length of characters.

Syntax: Strlen(string);

Example:  <?php echo strlen(“Welcome to PHP”);//will return 14 ?>

It’s important to note that the strlen() function returns the number of bytes rather than the number of characters. If each character is 1 byte, the number of bytes is the same as the number of characters.

However, if you deal with the multibyte string, e.g., UTF-8, the number of bytes is higher than the number of characters.

<?php

$message = 'んにこんにちは';

 echo strlen($message); // 21 bytes    

echo mb_strlen($message); // 7

?>

The strlen() function returns 21 bytes for the string 'んにこんにちは':

But the mb_strlen() function returns seven characters for that string:

2. str_word_count

You can display of the number of words in any specific string using str_word_count() function. This function is  also useful in validation of input fields.

Syntax: Str_word_count(string)

Example:

<?php echo str_word_count(“Welcome to Cloudways”);//will return 3 ?>

3. Strrev

Strrev() is used for reversing a string. You can use this function to get the reverse version of any string.

Syntax: Strev(string)

Example:

echo strrev(“Welcome to PHP”);// will return PHP ot emocleW

4. Strpos

Strpos() enables searching particular text within a string. It works simply by matching the specific text in a string. If found, then it returns the specific position. If not found at all, then it will return “False”.

Syntax: Strpos(string,text);

Example:

echo strpos(“Welcome to PHP”,”PHP”); // will return 11

5. Str_replace()

It is used for replacing specific text within a string.

Syntax: Str_replace(string to be replaced,text,string)

Example:

echo str_replace(“PHP”, “the programming world”, “Welcome to PHP”); // returns Welcome to the programming world

6. Ucwords()

It is used to convert first alphabet of every word into uppercase.

Syntax: Ucwords(string)

Example:

echo ucwords(“welcome to the php world”); // returns Welcome To The Php World

7. Strtoupper()

Strtoupper() is used to convert a whole string into uppercase.

Syntax: Strtoupper(string);

Example:

echo strtoupper(“welcome to php”); // returns WELCOME TO PHP

8. Strtolower()

Strtolower() is used to convert a string into lowercase.

Syntax: Strtolower(string)

Example:

echo strtolower(“WELCOME TO PHP”); // return welcome to php

9. Str_repeat()

It is used for repeating a string a specific number of times.

Syntax: Str_repeat(string,repeat)

Example:

echo str_repeat(“=”,12); // return ============

10. strcmp()

You can compare two strings by using strcmp(). It returns output either greater than zero, less than zero or equal to zero. If string 1 is greater than string 2 then it returns greater than zero. If string 1 is less than string 2 then it returns less than zero. It returns zero, if the strings are equal.

Syntax: Strcmp(string1,string2)

Example:

<?php 

echo strcmp(“Php”,”PHP”); // return 1

echo strcmp(“php”,”php”);// return 0

11. substr()

you can display or extract a string from a particular position.

Syntax: substr(string,start,length)

Example:

<?php

echo substr(“Welcome to PHP”,0,10). // returns Welcome to

12. trim()

It is used for remove white spaces and predefined characters from a both the sides of a string.

Syntax:

Example:

<?php $str = “Wordpess Hosting”;

echo $str . “<br>”;

echo trim(“$str”,”Wording”);

// returns
Wordpess Hosting

pess Host

13. htmlspecialchars()

To prevent XSS attacks, you should always escape the string from unknown sources such as user inputs. To escape a string for output, you use the htmlspecialchars() function.

XSS stands for cross-site scripting. It’s a kind of attack where a hacker injects malicious client code into a web page’s output.

htmlspecialchars() function convert special characters to HTML entities. See below example, where htmlspecialchars function used. if we directly print variable, then script can execute. this type of thing can help hackers to add malicious code.

<?php $comment = '<script>alert("Hello there");</script>'; echo htmlspecialchars($comment);

14. str_contains

he PHP str_contains() function checks if a string contains a substring.

The str_contains() function has the following parameters:

  • $haystack is the string to be checked.
  • $needle is the substring to search for in the input string $haystack.

The str_contains() function returns true if the $needle is in the $haystackfalse otherwise.

Note that str_contains() function has been available since PHP 8.0.0.

See below example:

<?php $haystack = 'PHP is cool.'; $needle = 'PHP'; $result = str_contains($haystack, $needle) ? 'is' : 'is not'; echo "The string {$needle} {$result} in the sentence.";

// returns The string PHP is in the sentence

PHP string functions provide a wealth of tools for manipulating, processing and transforming text data in web applications. By familiarizing yourself with the diverse range of string functions available, you can streamline your coding workflow, enhance string manipulation capabilities, and build more robust and efficient PHP applications.

This comprehensive guide has equipped you with the knowledge to handle basic string manipulation, perform advanced operations using regular expressions, work with multibyte strings, and follow best practices for effective string handling. Armed with this expertise, you’re ready to unleash the power of PHP string functions and take your coding skills to new heights. Happy coding with PHP string functions!

Hope it helps! Thanks 🙂

Write a Reply or Comment

Your email address will not be published. Required fields are marked *