in ,

PHP Strings

PHP Strings
PHP Strings

In this tutorial, you will learn about PHP Strings step by step. So without much to do, let’s get started.

A string is a sequence of characters, like “Hello world!”.


In this tutorial, you will learn-

PHP String Functions

In this chapter we will look some commonly used functions to manipulate strings.


strlen() – Return the Length of a String

The PHP strlen() function returns the length of a string.

Example
Return the length of the string “Hello world!”:

<?php
echo strlen("Hello world!"); // outputs 12
?>
<!DOCTYPE html>
<html>
<body>

<?php
echo strlen("Hello world!");
?> 
 
</body>
</html>

Str_word_count() – Count Words in a String

The PHP str_word_count() function counts the number of words in a string.

Example
Count the number of word in the string “Hello world!”:

<?php
echo str_word_count("Hello world!"); // outputs 2
?>
<!DOCTYPE html>
<html>
<body>

<?php
echo str_word_count("Hello world!");
?> 
 
</body>
</html>

Strrev() – Reverse a String

The PHP strrev() function reverses a string.

Example
Reverse the string “Hello world!”:

<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
<!DOCTYPE html>
<html>
<body>

<?php
echo strrev("Hello world!");
?> 
 
</body>
</html>

Strpos() – Search For a Text Within a String

The PHP strpos() function searches for a specific text within a string. If a match is found, the function returns the character position of the primary match. If no match is found, it will return FALSE.

Example
Search for the text “world” in the string “Hello world!”:

<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
<!DOCTYPE html>
<html>
<body>

<?php
echo strpos("Hello world!", "world");
?> 
 
</body>
</html>

Tip: The first character position in a string is 0 (no longer 1).


str_replace() – Replace Text Within a String

The PHP str_replace() function replaces some characters with some different characters in a string.

Example
Replace the text “world” with “Salman”:

<?php
echo str_replace("world", "Salman", "Hello world!"); // outputs Hello Salman!
?>
<!DOCTYPE html>
<html>
<body>

<?php
echo str_replace("world", "Salman", "Hello world!");
?> 
 
</body>
</html>

READ NEXT

PHP Installation

PHP Syntax

PHP Comments

PHP Variables

PHP Variables Scope


This is about PHP Strings, and we hope you have learned something from this tutorial and share your opinion about this tutorial. What do you think about it, and if you think this tutorial will help some of your friends, do share it with them.

salman khan

Written by worldofitech

Leave a Reply

PHP Data Types

PHP Data Types

PHP Numbers

PHP Numbers