WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP 5 Strings


A string is a sequence of characters, like "Hello PHP5! PHP supports string operations".


PHP String Functions


Get The Length of a String

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

The example below returns the length of the string "Hello world!":

Example

<?php
echo strlen("Hello php!"); // outputs 15
?>

The output of the code above will be: 15.


Count The Number of Words in a String

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

Example

<?php
echo str_word_count("Hello php!"); // outputs 3
?>

The output of the code above will be: 3.


Reverse a String

The PHP strrev() function reverses a string:

Example

<?php
echo strrev("Hello php!"); // outputs !php olleH
?>

The output of the code above will be: !phpolleH.


Search For a Specific 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 first match. If no match is found, it will return FALSE.

The example below searches for the text "world" in the string "Hello world!":

Example

<?php
echo strpos("Hello php!", "php"); // outputs 5
?>

The output of the code above will be: 5.

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


Replace Text Within a String

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

The example below replaces the text "world" with "Jully":

Example

<?php
echo str_replace("world", "Jully", "Hello world!"); // outputs Hello Jully!
?>

The output of the code above will be: Hello Jully!


Using the strpos() function

strpos() function is used to search for a string or character within a string.
<?php
   echo strpos("Hello world!","world");
?>