codescracker


php

PHP Strings



« Previous Tutorial Next Tutorial »


Strings in PHP, are basically a sequence of characters such as "i a string", "hello world", "hello php strings", "strings", etc.

PHP Strings Example

Here are some examples, based on strings in PHP. Let's first start with, how to find the length of the string in PHP.

Get the Length of String in PHP

To get the length of a string in PHP, use a function named strlen(). This function returns the length (total number of character) of the string. Here is an example, uses strlen() function to fing the length of the string in PHP:

<!DOCTYPE html>
<html>
<body>

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

Here is the output of the above PHP script:

11

Count Number of Words in String in PHP

To count total number of words present in the string in PHP, use a function called str_word_count(). This function counts total number of words present in the string in PHP. Here is an example, uses str_word_count() function to count words in string in PHP:

<!DOCTYPE html>
<html>
<body>

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

Since there are two words in the string "Hello, PHP!" , so it will display 2 as result:

2

Reverse String in PHP

To reverse a string in PHP, use a function named strrev(). This function reverses a string in PHP. Here is an example:

<!DOCTYPE html>
<html>
<body>

<?php
echo strrev("Hello World!, This is PHP");
?>  
  
</body>
</html>

It will display the following result:

PHP si sihT ,!dlroW olleH

Search for Specific Text within String in PHP

To search for the specific text present in the string in PHP, then use a function named strpos(). This function searches for a specific text within the string.

In case, if a match is found, then the function returns the character's position of the first match. And if no match is found, then it will return FALSE. Here is an example searches for the text "world" in the string "Hello World!, This is PHP":

<!DOCTYPE html>
<html>
<body>

<?php
echo strpos("Hello World!, This is PHP", "World");
?>  
  
</body>
</html>

It will produce the following result:

6

Replace Text within String in PHP

To replace text within string in PHP, then use a function named str_replace(). This function replaces some characters with some other characters in the string in PHP. Here is an example, replaces the text "world" with "PHP"

<!DOCTYPE html>
<html>
<body>

<?php
echo str_replace("World", "PHP", "Hello, World");
?>  
  
</body>
</html>

It will display the following result:

Hello, PHP

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test