PHP String Functions

String functions in a programming language allow us to manipulate string data. When it comes to PHP, it supports various string functions by default, which means that you do not have to install anything extra to use those string functions. In this tutorial, we will list all the PHP string functions. Also, you will learn the syntax of each PHP string function with appropriate examples. So, without further ado, let us get started! PHP String Functions

PHP String Functions

  • Addcslashes

This function will add backslashes before the specified characters within a string. Syntax:

string addcslashes ( string $str , string $charlist )

Example:

<?php
   echo addcslashes("Foo['.']", 'z..A');
?>
  • Addslashes

This function will add backslashes in front of the specified characters within a string. Syntax:

string addslashes ( string $str )

Example:

<?php
   $str = "Is your name sai Right?";
   echo addslashes($str);
?>
  • Bin2hex

This function allows you to convert binary data into its hexadecimal representation. Syntax:

string bin2hex ( string $str )

Example:

<?php
   $binary = "XXX";
   $hex = dechex(bindec($binary));   
   echo $hex;
?>

Output: 0

  • Chop

This function allows you to remove the whitespaces within a string, and its second parameter allows you to specify the characters that you want to remove as well. Syntax:

chop(string,charlist)

Example:

<?php
   $str = "XXX YYY!";
   echo chop($str,"YYY!");
?>

Output: XXX

  • Chr

This function allows you to convert an ASCII value to its equivalent character. Syntax:

string chr ( int $ascii )

Example:

<?php
   echo chr(76) . "<br>"; 
   echo chr(78) . "<br>"; 
   echo chr(0x50) . "<br>"; 
?>

Output:

L
N
P
  • Chunk split

This function allows you to split a string into chunks that are separated with a specified end string. Syntax:

string chunk_split ( string $body [, int $chunklen = 76 [, string $end = "\r\n" ]] )

Example:

<?php
   $str = "XXXYYY";
   echo chunk_split($str,1,".");
?>

Output

X.X.X.Y.Y.Y.
  • Convert cyr string

This function allows you to convert one Cyrillic character set to another. Syntax:

string convert_cyr_string ( string $str , string $from , string $to )

Example:

<?php
   $str = "www hello ";
   echo convert_cyr_string($str,'w','a'); 
?>

Output:

www hello
  • Convert uudecode

This function allows you to decode an encoded string. Syntax:

string convert_uudecode ( string $data )

Example:

<?php
   echo convert_uudecode("+22!L;W9E(%!(4\"$`\n`");
?>

Output:

I love PHP!
  • Count chars

This function allows you to provide information about the character that is used in a string. Syntax:

mixed count_chars ( string $string [, int $mode = 0 ] )
  • Crc32

With this function, you can calculate the 32-bit CRC for the provided string. Syntax:

crc32(string)

Example:

<?php
   $str = crc32("XXX");
   printf("%u\n",$str);
?>

Output:

2319231104
  • Crypt

This function allows you to do the hashing for the specified string. Syntax:

string crypt ( string $str [, string $salt ] )

Example:

<?php
   $input = XXX;  
   $hash = crypt($input);
?>
  • Echo

With this function, you can display the string or character that you pass to this function. It can be more than one string. Syntax:

void echo ( string $arg1 [, string $... ] )

Example:

<?php
Echo (“hello”);
?>

Output:

hello
  • Explode

This function allows you to split a string with the help of another string and output the result in the form of an array. Syntax:

array explode ( string $delimiter , string $string [, int $limit ] )

Example:

<?php
   $str = "XXX YYYZZZ";
   print_r (explode(" ",$str));
?>

Output:

Array
(
    [0] => XXX
    [1] => YYYZZZ
)
  • Fprintf

This function allows you to write a formatted string to a stream. Syntax:

 int fprintf ( resource $stream , string $format [, mixed $args [, mixed $... ]] )

Example:

<?php
   $f_name = 123;
   $file = fopen("index.txt","r");
   fprintf($file,"%f",$f_name);
?>
  • Get html translation table

This function provides you with a translation table that is used by htmlspecialchars() and htmlentities() functions. Syntax:

array get_html_translation_table ([ int $table = HTML_SPECIALCHARS [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = "UTF-8" ]]] )

Example:

<?php
   print_r (get_html_translation_table(HTML_DATA));
?>
  • Hebrev

With this function, you can convert a logical Hebrew text to visual text. Syntax:

string hebrev ( string $hebrew_text [, int $max_chars_per_line = 0 ] )

Example:

<?php
   print_r (hebrev(HTML_SPECIALCHARS));
?>

Output: 0

  • Hebrevc

This function allows you to convert a logical Hebrew text to visual text along with newline conversion. Syntax:

string hebrevc ( string $hebrew_text [, int $max_chars_per_line = 0 ] )

Example:

<?php
   print_r (hebrevc(HTML_SPECIALCHARS));
?>

Output:

0
  • Hex2bin

This function allows you to convert a hexadecimal string to an ASCII character. Syntax:

string hex2bin ( string $data )

Example:

<?php
   $hex = hex2bin("43480170");
   var_dump($hex);
?>

Output:

string(4) "CHp"
  • HTML entity decode

This function allows you to convert HTML entities to application characters. Syntax:

string html_entity_decode ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") ]] )

Example:

<?php
   $input_string = "xxx \"point\" simple <b>pattern</b> learning";
   $ab = htmlentities($input_string);
   $b = html_entity_decode($ab);
   echo $ab;
?>

Output:

xxx "point" simple <b>pattern</b> learning
  • HTML special chars decode

This function allows you to convert special HTML entities to characters. Syntax:

string htmlspecialchars_decode ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 ] )

Example:

<?php
   $input = "<p>data -> </p>\n";
   echo htmlspecialchars_decode($input);
?>

Output:

data ->
  • Implode

With this function, you can join array elements with a string. Syntax:

string implode ( array $pieces )

Example:

<?php
   $a1 = array("1","2","3");
   echo "a1 is: '".implode("','",$a1)."'<br>";
   ?>

Output:

a1 is: '1','2','3'
  • Join

This function is an alias of the implode() function, and it returns a string from the elements of an array specified within the input parameter. Syntax:

join(separator,input)

Example:

<?php
   $data = inputay('xxx','yyy','abc');   
   echo join(" ",$data);
?>

Output:

xxx yyy abc
  • Lcfirst

This function allows you to convert a string's first character into lowercase. Syntax:

string lcfirst ( string $str )

Example:

<?php
   $input_string = 'XXXYYY';
   $input = lcfirst($input_string);    
   echo $input;
?>

Output: xXXYYY

  • Levenshtein

This function allows you to calculate the Levenshtein distance between two strings. Syntax:

 int levenshtein ( string $str1 , string $str2 )

Example:

<?php
   echo 'distance is ';
   echo levenshtein("strings","duostrings");
?>

Output:

distance is 3
  • Localeconv

This function provides you with the numeric formatting information of a string. Syntax:

array localeconv ( void )

Example:

<?php
   setlocale(LC_ALL,"US");
   $demo = localeconv();
   print_r($demo);
?>

Output:

Array ( [decimal_point] => . [thousands_sep] => [int_curr_symbol] => [currency_symbol] => [mon_decimal_point] => [mon_thousands_sep] => [positive_sign] => [negative_sign] => [int_frac_digits] => 127 [frac_digits] => 127 [p_cs_precedes] => 127 [p_sep_by_space] => 127 [n_cs_precedes] => 127 [n_sep_by_space] => 127 [p_sign_posn] => 127 [n_sign_posn] => 127 [grouping] => Array ( ) [mon_grouping] => Array ( ) )
  • ltrim

This function allows you to trim the whitespace or other characters from the beginning of a string. The second parameter specifies the character that you want to trim. Syntax:

string ltrim ( string $str [, string $character_mask ] )

Example:

<?php
   $str = "XXX YYY ZZZ!";
   echo ltrim($str,"demo");
?>

Output:

XXX YYY ZZZ!
  • Md5_file

This function allows you to specify the md5 hash calculation for a file. Syntax:

string md5_file ( string $filename [, bool $raw_output = false ] )

Example:

<?php
   $data = "demo.txt";
   $file = md5_file($data);
   echo $file;
?>
  • Md5

This function calculates the md5 hash of a string. Syntax:

string md5 ( string $str [, bool $raw_output = false ] )

Example:

<?php
   $str = "XXXYYY";
   echo md5($str);
?>

Output:

be8f96a5286fd728317f4f08b8588e70
  • Metaphone

This function lets you calculate the Metaphone key of a string. Syntax:

string Metaphone ( string $str [, int $phonemes = 0 ] )

Example:

<?php
   echo metaphone("Study simple");
?>

Output:

STTSMPL
  • Money format

This function formats a number as a currency string according to the provided format within the function. Syntax:

string money_format ( string $format , float $number )

Example:

<?php
   $data = 257.10;
   setlocale(LC_MONETARY,"de_DE");
   echo money_format("%.2n", $data);
?>

Output:

257.10
  • NL langinfo

This function allows you to get information about language and locale. Syntax:

string nl_langinfo ( int $item )
  • Nl2br

This function allows you to insert the HTML line breaks before all the newlines in a string. Syntax:

 string nl2br ( string $string [, bool $is_xhtml = true ] )

Example:

<?php
   echo nl2br("xxx.\nAnother line."); 
?>

Output:

xxx.
Another line.
  • Number format

You can use this function to format a given number with grouped thousands. Syntax:

inputber_format(inputber,decimals,decimalpoint,separator)

Example:

<?php
   $data = 1000.9;
   $f_data = inputber_format($data) ;
   echo $f_data;
   $f_data = inputber_format($data, 2);
   echo $f_data;
?>
  • Ord

This function lets you provide the ASCII value of a provided character or string. Syntax:

int ord ( string $string )

Example:

<?php
   echo ord("hi")."<br>";
?>

Output:

104
  • Parse str

This function allows you to parse a string into variables. Syntax:

void parse_str ( string $str [, array &$arr ] )

Example:

<?php
   parse_str("name1=Jacob Sons&age=45");
   echo $name1."<br>";
   echo $age;
?>

Output:

Jacob Sons
45
  • Print

This function allows you to provide the output with a string that is passed within the function. Syntax:

int print ( string $arg )

Example:

<?php
   print "Hello"; 
?>

Output:

Hello
  • Printf

This function provides you with the output of a formatted string according to the format parameter. Syntax:

int printf ( string $format [, mixed $args [, mixed $... ]] )

Example:

<?php
   printf("Study section");
?>

Output:

Study section
  • Quoted printable decode

This function converts a quoted printable string to its corresponding 8-bit string. Syntax:

string quoted_printable_decode ( string $str )

Example:

<?php
   $input = "XXX = YYY.";
   echo quoted_printable_decode($input);
?>

Output:

XXX = YYY.
  • Quoted printable encode

This function converts an 8-bit string to the quoted printable string. Syntax:

string quoted_printable_encode ( string $str )

Example:

<?php
   $input = "yyy = xxx.";
   echo quoted_printable_encode($input);
?>

Output:

yyy =3D xxx.
  • Quotemeta

This function allows you to quote metacharacters. Syntax:

string quotemeta ( string $str )

Example:

<?php
   $input = "study. and learning";
   echo quotemeta($input);
?>

Output:

study\. and learning
  • Rtrim

With this function, you can trim the white spaces from the end of a string. Syntax:

string rtrim ( string $str [, string $character_mask ] )

Example:

<?php
   $data = "hi bye";
   echo $data . "<br>";
   echo rtrim($data,"bye");
?>

Output:

hi bye
hi
  • Setlocale

This function allows you to set the locale information. Syntax:

string setlocale ( int $category , array $locale )

Example:

<?php
   echo setlocale(LC_ALL,"UK");
   echo "<br>";
   echo setlocale(LC_ALL,NULL);
?>

Output:

en_US.UTF-8
  • Sha1 file

This function calculates the sha1 hash of a file. Syntax:

sha1_file(string $filename) 

Example:

<?php
   $data = "demo.txt";
   $s_file = sha1_file($data);
   echo $s_file;
?>
  • Sha1

This function will allow you to calculate the sha1 hash of a string. Syntax:

string sha1 ( string $str [, bool $raw_output = false ] )

Example:

<?php
   $data = "hello";
   $s_file = sha1($data);
   echo $s_file;
?>

Output:

aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
  • Similar text

This function will allow you to calculate the similarity between two strings Syntax

 int similar_text ( string $first , string $second [, float &$percent ] )

Example

<?php
   echo similar_text("study","park");
?>

Output

0
  • Soundex

This function allows you to provide the soundex key of a string. Syntax:

string Soundex ( string $str )

Example:

<?php
   $data = "XXX";
   echo soundex($data);
?>

Output:

X000
  • Sprintf

With this function, you can format a string Syntax:

string sprintf ( string $format [, mixed $args [, mixed $... ]] )

Example:

<?php
   $num = 123;
   $data = sprintf("%f",$num);
   echo $data;
?>

Output:

123.000000
  • Str  getcsv

This function allows you to parse a CSV string into an array. Syntax:

array str_getcsv ( string $input [, string $delimiter = ","  [, string $enclosure = '"' [, string $escape = "\\" ]]] )

Example:

<?php
   $data = array_map('str_getcsv', file('Str.csv'));
?>
  • Str ireplace

With this function, you can find certain characters in a string and replace them with some other characters. Syntax:

str_ireplace(find,replace,string,count)

Example:

<?php
   $input = array("XXX","point","simple","easy");
   print_r(str_ireplace("simply","XXX",$input,$i)); // Case-insensitive   
   echo "<br>" . "Replacements: $i";  
?>

Output:

Array ( [0] => XXX [1] => point [2] => simple [3] => easy )
Replacements: 0
  • Str pad

This function allows you to pad a string to a new length. Syntax:

str_pad(string,length,pad_string,pad_type)

Example:

<?php
   $input = "learning data ";
   echo str_pad($input,18,"!!"); 
?>

Output:

learning data !!!!
  • Str repeat

This function allows you to repeat a string. Syntax:

str_repeat(string,length,pad_string,pad_type)

Example:

<?php
   echo str_repeat("XXX",5);
?>

Output:

XXXXXXXXXXXXXXX
  • Str replace

This function lets you replace a string present within another string. Syntax:

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

Example:

<?php
   echo str_replace("park","YYY","XXX park");
?>

Output:

XXX YYY
  • Str rot13

This function allows you to perform the rot13 transform on a string. Syntax:

string str_rot13 ( string $str )

Example:

<?php

   echo str_rot13('PHP 7'); 

?>

Output:

CUC 7
  • Str shuffle

This function randomly shuffles a string. Syntax:

string str_shuffle ( string $str )

Example:

<?php
   $data = 'abcdefphp_function_str_shuffle';
   $var = str_shuffle($data);
   echo $var;
?>

Output:

edhcsnfircunuthfe_spbfo_ftpa_l
  • Str split

This function allows you to convert a string to an array. Syntax:

array str_split ( string $string [, int $split_length = 1 ] )

Example:

<?php

   print_r(str_split("XXXYYY"));

?>

Output:

Array ( [0] => X [1] => X [2] => X [3] => Y [4] => Y [5] => Y )
  • Str word count

This function provides information about the words used in a string. Syntax:

mixed str_word_count ( string $string [, int $format = 0 [, string $charlist ]] )

Example:

<?php
   echo str_word_count("simple study easy learning");
?>

Output:

4
  • Strcasecmp

This function compares two strings. Syntax:

int strcasecmp ( string $str1 , string $str2 )

Example:

<?php
   echo strcasecmp("Hello world!","study WORLD!");
?>

Output:

-11
  • Strchr

This function allows you to search for the first occurrence of a string within another string. Syntax:

strchr(string,search,before_search);

Example:

<?php
   echo strchr("Hello world!","world");
?>

Output:

world!
  • Strcmp

This function allows you to compare the two provided strings. Syntax:

strcmp(string1,string2)

Example:

<?php
  $var=  strcmp("Hello world!","Hello world!");
Echo $var;
?>

Output:

0
  • Strcoll

This function compares two strings based on locale settings. Syntax:

int strcoll ( string $str1 , string $str2 )

Example:

<?php
     setlocale (LC_COLLATE, 'NL');
   $var=  strcoll("Hello World!","Hello World!");
Echo $var;
?>

Output:

0
  • Strcspn

This function returns a number of characters of a string before any part of the specified characters is found. Syntax:

strcspn(string,char,start,length)

Example:

<?php
   echo strcspn("XXX will simple easy learning","r");
?>

Output:

24
  • Strip tags

This function allows you to strip the HTML and PHP tags from a string. Syntax:

string strip_tags ( string $str [, string $allowable_tags ] )

Example:

<?php
   echo strip_tags("XXX <b><i>YYY</i></b>","<b>");
?>

Output:

XXX YYY
  • Stripcslashes

This function removes backslashes from a string. Syntax:

string stripcslashes ( string $str )

Example:

<?php
   echo stripcslashes("Hello \World!");
?>

Output:

Hello World!
  • Stripos

This function allows you to find the position of a string’s first occurrence inside another string. Syntax:

stripos(string,find,start)

Example:

<?php
   echo stripos("java courses","java");
?>

Output:

0
  • Stripslashes

This function un-quote a quoted string. Syntax:

string stripslashes ( string $str )

Example:

<?php
   echo stripcslashes("XXX \YYY");
?>

Output:

XXX YYY
  • Stristr

This function allows you to find the first occurrence of a string inside another string. Syntax:

string stristr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

Example:

<?php
   echo stristr("sairam krishna","krishna",true);
?>

Output:

sairam
  • Strlen

With this function, you can find the length of a string. Syntax:

int strlen ( string $string )

Example:

<?php
   $var = “hello”;
      echo strlen($var);
?>

Output:

5
  • Strnatcasecmp

This function allows you to compare two strings with a natural algorithm. Syntax:

strnatcasecmp(string1,string2)

Example:

<?php
   echo strnatcasecmp("hwllo", "bye");
?>

Output:

1
  • Strnatcmp

This function allows you to compare the two strings with a natural order algorithm. Syntax:

int strnatcmp ( string $str1 , string $str2 )

Example:

<?php
   echo strnatcmp("Jacob2", "sami1");
?>

Output:

-1
  • Strncasecmp

This function compares two strings. It takes three parameters, where the first two parameters are the strings and the third parameter specifies the number of characters to be matched from both the strings. Syntax:

strncasecmp(string1,string2,length)

Example:

<?php
   echo strncasecmp("work!","thinking!",6);
?>

Output:

3
  • Strncmp

This function compares the first n characters of the given strings. It takes three parameters, where the first two parameters are the strings and the third parameter specifies the number of characters to be matched from both the strings. Syntax:

int strncmp ( string $str1 , string $str2 , int $len )

Example:

<?php

   echo strncmp("work","working",6);

?>

Output:

-2
  • Strpbrk

With this function, you can search a string for a specific character. Syntax:

string strpbrk ( string $haystack , string $char_list )

Example:

<?php
   echo strpbrk("Input","I");
?>

Output:

Input
  • Strpos

This function allows you to find the position of the first occurrence of a string within another string. Syntax:

strpos(string,find,start)

Example:

<?php
   echo strpos("simple learning easy !","easy");
?>

Output:

16
  • Strrchr

This function allows you to find the last occurrence of a string within a provided string. Syntax:

strrchr(string,char)

Example:

<?php

   echo strrchr("hello Jacob!","Jacob");

?>

Output:

Jacob
  • Strrev

This function allows you to reverse a string. Syntax:

string strrev ( string $string )

Example:

<?php
   echo strrev("study well");
?>

Output:

llew yduts
  • Strripos

This function allows you to find the last occurrence of a string inside another string. Syntax:

strripos(string,find,start)

Example:

<?php
   echo strripos("work hard, HARD WORK","work");
?>

Output:

16
  • Strspn

This function allows you to find the number of characters present in the string specified by the charlist parameter. Syntax:

strspn(string,charlist,start,length)

Example:

<?php
   echo strspn("Learning tutorial","t");
?>

Output:

0
  • Strstr

This function lets you find the first occurrence of a given string. Syntax:

strstr(string,search,before_search)

Example:

<?php
   echo strstr("sam",111);
?>
  • Strtok

This function split the string on the basis of the given split character. Syntax:

strtok(string,split)

Example:

<?php
   $var = "simple courses";
   $var1 = strtok($var, " ");
   while ($var1 !== false){
      echo "$var1<br>";
      $var1 = strtok(" ");
   }
?>

Output:

simple
courses
  • Strtolower

This function allows you to convert a string to lowercase. Syntax:

strstr(string,search,before_search)

Example:

<?php
   echo strtolower("XXX YYY.");
?>

Output:

xxx yyy
  • Strtoupper

This function allows you to convert a string to uppercase. Syntax:

string strtoupper ( string $string )

Example:

<?php
   echo strtoupper("xxx yyy.");
?>

Output:

XXX YYY
  • Strtr

This function allows you to translate characters or replace a substring. Syntax:

strtr(string,from,to)

Example:

<?php
   echo strtr("sam","a","e");
?>

Output:

sem
  • Substr_compare

This function allows you to compare two given string formats starting from a specific position. Syntax:

substr_compare(string1,string2,startpos,length,case)

Example:

<?php
   echo substr_compare("work hard","work",2);
?>

Output:

-1
  • Substr_count

This function allows you to count the number of substrings present within a string starting from the start position until the given length. Syntax:

substr_count(string,substring,start,length)

Example:

<?php
   echo substr_count("workhard","work");
?>

Output:

1
  • Substr_replace

This function allows you to replace a part of a string with another string. Syntax:

substr_replace(string,replacement,start,length)

Example:

<?php
   echo substr_replace("study simple","Study Simple",0);
?>

Output:

Study Simple
  • Substr

This function allows you to provide the substring of a string. Syntax:

string substr ( string $string , int $start [, int $length ] )

Example:

<?php
   echo substr("Simple Study",6);
?>

Output:

Study
  • Trim

With this function, you can remove the whitespaces and other characters in a string. Syntax:

trim(string,charlist)

Example:

<?php
   $input = "simple study";
   echo trim($input,"study");
?>

Output:

imple
  • Ucfirst

This function allows you to convert only the first character of a string to uppercase. Syntax:

ucfirst(string)

Example:

<?php
   echo ucfirst("working");
?>

Output:

Working
  • Ucwords

This function allows you to convert only the first character of each word in a string to the upper case. Syntax:

ucwords(string)

Example:

<?php
   echo ucwords("let us work");
?>

Output:

Let Us Work
  • Vfprintf

This function converts a formatted string to a specific output. Syntax:

vprintf(format,argarray)

Example:

<?php
   $number = 22;
   $str = "Simple Study";
   vprintf("There are %u million users for %s.",array($number,$str));
?>

Output: There are 22 million users for Simple Study.

  • Vsprintf

This function allows you to provide a formatted string. Syntax:

string vsprintf ( string $format , array $args )

Example:

<?php
   print vsprintf("%04d-%02d-%02d", explode('-', '2022-02-14'));
?>

Output:

2022-02-14
  • Wordwrap

This function allows you to break the long words and arrange them in the next lines. Syntax:

wordwrap(string,width,break,cut)

Example:

<?php
   $str = "simple study";
   echo wordwrap($str,5,"<br>\n",TRUE);
?>

Output:

simpl
e
study

Conclusion

So, the above listed are the various PHP string functions that you must know if you want to work with PHP. With these string functions, you can perform a variety of operations on the strings. If you have any queries or doubts related to the PHP string mentioned in this article, you can share them with us in the comments section below.

People are also reading: