Home » Web development » PHP » Useful PHP string functions

Useful PHP string functions

Here are detailed working on useful PHP string functions

strlen()

The PHP strlen() function returns the length of a string.
The example below returns the length of the string “john”
Example

<?php
echo strlen("John");
?>

Output
4

Chr()

Converts an ASCII value to its equivalent character

Example

The ASCII value 46 is the & symbol

<?php
$str = chr(046);
echo("the value are 1 $str 2");
?>

Output
the value are 1 & 2

strrev()

It reverses the string

Example

<?php
echo strrev("John");
?>

Output
nohj

Substr()

The substr() function returns a part of a string

substr(string,start,length)


start: where to start in the string
Length: length of the returned string. Default is to the end of the string
This is optional. If you miss it out, you’ll grab all the characters to the end of the string.

Example

<?php
substr("John",1,3);
?>

Output
Joh

str_word_count()

The str_word_count () function tells you how many words a string has.

Example

<?php
str_word_count("how are you");
?>

Output
3

str_replace()

The str_replace() function in PHP allows you to replace one string with another.

str_replace( $look_for, $change_to, $search_text );

Example

<?php
str_replace("John","Matt", "John is absent");
?>

Output
Matt is absent

strops()

  • The PHP strpos() function searches for a specific text within a string.
  • If the function can find a search match, then it will return the position of the first match. However, if it can’t find a match it will return false
strpos ('string', 'match_pattern', [offset])

The optional offset parameter tells the function to start looking for the match after the offset-th character in the string. The value returned by the function still indicates the position of the first match relative to the entire string.

See also  How to define constant in php

Example

<?php
strpos("today is monday","mon" );
?>

Output
8

In this example, the match occurs at the 9 place string, hence the function returns 8 as numbering starts from 0

Hope you like post on PHP string functions

Also Reads
How to run php file in windows : This post talks about how we can php file on the the window and do the testing before moving to the web server
uses of PHP : This has detailed description why PHP is so much used through out the world.
first php program : This is good starting point for anybody starting with PHP and talk in good detail about how to write your PHP program and execute it
Define constant in PHP
PHP Array functions
https://en.wikipedia.org/wiki/PHP

Leave a Comment

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

Scroll to Top