Related Tags

php
communitycreator

# What are the string functions in PHP?

### Overview

A string can be defined as a combination of characters. We'll look into some commonly used string functions in PHP.

### 1.str_word_count()

This function counts the words in a string.

### Example

Let's look at the code below:

<?php
echo str_word_count("Learn from Educative!"); // outputs 3
?>

### Explanation

There are 3 words in this string "Learn from Educative!".

### 2.strlen()

This function returns the length of a string.

### Example

Let's look at the code below:

<?php
echo strlen("Learn from Educative!"); // outputs 21
?>

### Explanation

The length of the string "Learn from Educative!" is returned. In this case, the length returned is 21 characters.

### 3.strpos()

This function searches the given string from the larger(main) string. Character position of the first match is returned, otherwise, false is returned.

### Example

Let's look at the code below:

<?php
echo strpos("Learn from Educative!", "Educative"); // outputs 11
?>

### Explanation

The first character position in a string is 0. Keeping this in mind, "Educative" starts from the $11_{th}$ character position in the main string.

### 4.strrev()

This function will reverse a string.

### Example

Let's look at the code below:

<?php
echo strrev("Learn from Educative!"); // outputs !evitacudE morf nraeL
?>

### Explanation

It reverses the given string "Learn from Educative!".

### 5.str_replace()

This function will replace some characters with some other characters in a string.

### Example

Let's look at the code below:

<?php
echo str_replace("from", "through", "Learn from Educative!"); // outputs Hello Dolly!
?>

### Explanation

It replaces the word "from" with "through" in the string.

RELATED TAGS

php
communitycreator

CONTRIBUTOR