Showing posts with label PHP String Functions. Show all posts
Showing posts with label PHP String Functions. Show all posts

Monday, 5 August 2019

Useful strings function in PHP

Here are detailed working on useful strings functions in PHP

FunctionDescription and working
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 64 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
nhoJ
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 firstmatch. 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.
Example
<?php
str_replace(“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

Friday, 2 August 2019

How to get the last character in a string using PHP

  • This can be done by using the substr which will return a part of a string.
  • The sample code below will return the letter f
    $lastChar= substr("abcdef", -1);
    The -1 is negative, the returned string will start at the last character from the end of the string.

[function.file-put-contents]: failed to open stream: File name too long

Error: [<a href=’function.file-put-contents’>function.file-put-contents</a>]: failed to open stream: File name too long
To solve this error you need to rename the filename so that the filename and extention together are no more than 255 characters, an easy way to do this is
$filename=substr($name,0,251).'.pdf';
Note, that we used the character count 251 since 251 + the 4 characters for the extention together add up to 255 characters.

Monday, 20 July 2015

PHP Functions for Words Formatting

PHP functions are used for text formatting. Formatting like uppercase, lowercase and first letter uppercase can also be done using php functions, here is the 5 php functions for words/text formatting
  • ucwords
  • strtoupper
  • strtolower
  • ucfirst
  • lcfirst
ucwords()
Make each word’s first letter as capital letter
1
2
3
4
$text = "freeze coders";

$text1 = ucwords($text)// Output -  Freeze Coders

strtoupper()
strtoupper php function will make all words as upper case(capital letter)
1
2
3
4
$text = "freeze coders";

$text1 = strtoupper($text)// Output -  FREEZE CODERS

strtolower()
strtolower php function will make all words as lower case(capital letter)
1
2
3
4
$text = " FREEZE CODERS";

$text1 = strtolower($text)// Output -  freeze coders

ucfirst()
ucfirst php function will make the first letter of a string as uppercase
1
2
3
4
$text = "freeze coders";

$text1 = ucfirst($text)// Output -  Freeze coders

lcfirst()
lcfirst() php function will return the string’s first letter lowercase
1
2
3
4
$text = " FREEZE CODERS";

$text1 = lcfirst($text)// Output -  fREEZE CODERS

Friday, 26 June 2015

PHP: Trim A String with PHP

<?php
/* 
Example usage: 

$long_string="This is a very long string that I want shortened"; 
$short_string=trimString($long_string, 10); 

echo $short_string;  

Will output "This is..." 
*/ 
function trimString($str, $len) { 
    If(strlen($str)>intval($len)) { 
            return(substr($str,0,($len-3))."..."); 
    } 
    return($str); 
?>

PHP: Some useful PHP functions

Regular expressions are a powerful tool for examining and modifying text. preg_match is a powerful function of PHP that performs a regular expression match. Let’s have a short look on the syntax of preg_match before digging some interesting, practical and useful examples.
Syntax of preg_match
 
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

As my focus of this post is to share handy and useful examples of preg_match, so i am not going to discuss about the arguments of preg_match in detail. But i am sure you will learn them with the following examples professionally.
1. Find a String in a String

Find a string in a string can be done very easily by preg_match. Let’s have a look at the following two examples.

Useful Tip

    The "i" after the pattern delimiter indicates a case-insensitive search

   
/*
|---------------------
| Case Sensitive Search
|---------------------
*/

if ( preg_match("/cool/", "I love to share Cool things that help others. @lifeobject1") ) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}

echo "<br />";

/*
|---------------------
| Case Insensitive Search
|---------------------
*/

if ( preg_match("/cool/i", "I love to share Cool things that help others. @lifeobject1") ) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}

Output

Output of above examples will be,

A match was not found.
A match was found.
2. Find a Word in a String

Find a word in a string is a hot and regular requirement in the php development. PHP beautifully provides this solution and we will achieve this task by the following two examples of preg_match.

Useful Tip

    The "\b" in the pattern indicates a word boundary, so only the distinct


/*
|---------------------
| Word "profession" is matched, and not a word partial like "professional" or "professionalism"
|---------------------
*/

if ( preg_match("/\bprofession\b/i", "I am Software Engineer by profession. @lifeobject1") ) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}

echo "<br />";

/*
|---------------------
| Word "profession" is matched, and not a word partial like "professional" or "professionalism"
|---------------------
*/

if ( preg_match("/\bprofession\b/i", "My professional ethic is sharing. @lifeobject1") ) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}

Output

Output of above examples will be,
   
A match was found.
A match was not found.
3. Find Domain Name from URL

PHP developers often require to find a domain name from URL. preg_match provides a very easy solution. Let’s have a look into following examples.

Useful Tip

    If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

   
/*
|---------------------
| Get host name from URL
|---------------------
*/

preg_match( '@^(?:http://)?([^/]+)@i', "http://www.tutorialchip.com/category/php/", $matches );
$host = $matches[1];

echo "Host name is: " . $host;
echo "<br />";

/*
|---------------------
| Get last two segments of host name
|---------------------
*/

preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "Domain name is: " . $matches[0];

Output

Output of above examples will be,
1
2
   
Host name is: www.tutorialchip.com
Domain name is: tutorialchip.com
4. Valid IP Address Check

preg_match makes the validity of IP address very easy. Let’s have a look into the following method which returns the validity of IP address professionally.

Useful Tip

    Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.

   
/*
|---------------------
| Valid IP Method
|---------------------
*/

function get_valid_ip( $ip ) {
    return preg_match("/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])" .
            "(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/", $ip );
}

/*
|---------------------
| Valid IP Example
|---------------------
*/

$ip = "192.168.1.1";
if ( get_valid_ip( $ip ) ) {
    echo $ip . " is valid.";
}

echo "<br />";

/*
|---------------------
| Invalid IP Example
|---------------------
*/

$ip = "256.168.1.1";
if ( ! get_valid_ip( $ip ) ) {
    echo $ip . " is not valid.";
}

Output

Output of above examples will be,
1
2
   
192.168.1.1 is valid.
256.168.1.1 is not valid.
5. US Phone Number Format Example

Getting a US phone number format is a tough task as user may input phone number in different formats. Let’s have a look at the power of preg_match. You will notice a usage of preg_replace for the sake of getting US phone number format.

   
/*
|---------------------
| US Phone Number Format Regex
|---------------------
*/

$regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})'
        .'(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})'
        .'[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';

/*
|---------------------
| Different Formats
|---------------------
*/

$formats = array(
        '520-628-4539', '520.628.4539', '5206284539' ,
        '520 628 4539', '(520)628-4539', '(520) 628-4539',
        '(520) 628 4539', '520-628.4539', '520 628-4539',
        '(520)6284539', '520.628-4539', '15206284539',
        '1 520 628 4539', '1.520.628.4539', '1-520-628-4539',
        '520-628-4539 ext.123', '520.628.4539 EXT 123 ', '5206284539 Ext. 5889',
        '520 628 4539 ext 8', '(520) 628-4539 ext. 456', '1(520)628-4539'
        );

/*
|---------------------
| Let's Format Them
|---------------------
*/

foreach( $formats as $phoneNumber ) {

    if( preg_match($regex, $phoneNumber) ) {
        echo "Phone Number Matched " . $phoneNumber . " - US Format: " .  preg_replace($regex, '($1) $2-$3 ext. $4', $phoneNumber);
        echo "<br />";
    }

}

Output

Output of above examples will be,

   
Phone Number Matched 520-628-4539 - US Format: (520) 628-4539 ext.
Phone Number Matched 520.628.4539 - US Format: (520) 628-4539 ext.
Phone Number Matched 5206284539 - US Format: (520) 628-4539 ext.
Phone Number Matched 520 628 4539 - US Format: (520) 628-4539 ext.
Phone Number Matched (520)628-4539 - US Format: (520) 628-4539 ext.
Phone Number Matched (520) 628-4539 - US Format: (520) 628-4539 ext.
Phone Number Matched (520) 628 4539 - US Format: (520) 628-4539 ext.
Phone Number Matched 520-628.4539 - US Format: (520) 628-4539 ext.
Phone Number Matched 520 628-4539 - US Format: (520) 628-4539 ext.
Phone Number Matched (520)6284539 - US Format: (520) 628-4539 ext.
Phone Number Matched 520.628-4539 - US Format: (520) 628-4539 ext.
Phone Number Matched 15206284539 - US Format: (520) 628-4539 ext.
Phone Number Matched 1 520 628 4539 - US Format: (520) 628-4539 ext.
Phone Number Matched 1.520.628.4539 - US Format: (520) 628-4539 ext.
Phone Number Matched 1-520-628-4539 - US Format: (520) 628-4539 ext.
Phone Number Matched 520-628-4539 ext.123 - US Format: (520) 628-4539 ext. 123
Phone Number Matched 5206284539 Ext. 5889 - US Format: (520) 628-4539 ext. 588
Phone Number Matched 520 628 4539 ext 8 - US Format: (520) 628-4539 ext. 8
Phone Number Matched (520) 628-4539 ext. 456 - US Format: (520) 628-4539 ext. 456
Phone Number Matched 1(520)628-4539 - US Format: (520) 628-4539 ext.
6. Valid Email Address Regex

Email address validation is a regular requirement of PHP developers. Let’s see at following example.

Useful Tip

    Because making a truly correct email validation function is harder than one may think, consider using with pure PHP through the filter_var function.

   
/*
|---------------------
| Valid Email Address Regex
|---------------------
*/

function get_valid_email( $email ) {
  $regex = '/^([*+!.&#$¦\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/i';
  return preg_match($regex, trim($email), $matches);
}

/*
|---------------------
| Different Emails
|---------------------
*/

$emails = array(
            'my.name@gmail.com',
            'another@gmail.co.uk',
            'best@yahoo',
            'hellomsn.net',
            'long@123.org',
            '123.me.you@ymail.com',
            'miss@yahoo.',
        );

/*
|---------------------
| Let's Check Them
|---------------------
*/

foreach( $emails as $email ) {

    if( get_valid_email( $email ) ) {
        echo "Valid Email: " . $email;
    }

    else {
        echo "Invalid Email: " . $email;
    }

    echo "<br />";

}

Output

Output of above examples will be,

   
Valid Email: my.name@gmail.com
Valid Email: another@gmail.co.uk
Invalid Email: best@yahoo
Invalid Email: hellomsn.net
Valid Email: long@123.org
Valid Email: 123.me.you@ymail.com
Invalid Email: miss@yahoo.
Out of the Box: Email Address Validation with PHP filter_var function

Let’s see at following example of email address validation with PHP through the filter_var function.

   
/*
|---------------------
| Valid Email Address filter_var
|---------------------
*/

function get_valid_email( $email ) {
  return filter_var( $email, FILTER_VALIDATE_EMAIL );
}

/*
|---------------------
| Different Emails
|---------------------
*/

$emails = array(
            'my.name@gmail.com',
            'another@gmail.co.uk',
            'best@yahoo',
            'hellomsn.net',
            'long@123.org',
            '123.me.you@ymail.com',
            'miss@yahoo.',
        );

/*
|---------------------
| Let's Check Them
|---------------------
*/

foreach( $emails as $email ) {

    if( get_valid_email( $email ) ) {
        echo "Valid Email: " . $email;
    }

    else {
        echo "Invalid Email: " . $email;
    }

    echo "<br />";

}

Output

Output of above examples will be,

   
Valid Email: my.name@gmail.com
Valid Email: another@gmail.co.uk
Invalid Email: best@yahoo
Invalid Email: hellomsn.net
Valid Email: long@123.org
Valid Email: 123.me.you@ymail.com
Invalid Email: miss@yahoo.
7. Validate URL Regular Expression

We can use preg_match for the validation of any type of URL. Let’s have a look into the code snippet of PHP URL Valdation.

   
/*
|---------------------
| Validate URL Regular Expression
|---------------------
*/

function get_valid_url( $url ) {

    $regex = "((https?|ftp)\:\/\/)?"; // Scheme
    $regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
    $regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP
    $regex .= "(\:[0-9]{2,5})?"; // Port
    $regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
    $regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
    $regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor

    return preg_match("/^$regex$/", $url);

}

/*
|---------------------
| Different URLs
|---------------------
*/

$urls = array(

            'https://thiscode4u.blogspot.com/',

            'https://thiscode4u.blogspot.com/php-csv-parser-class/#tab-description',

            'http://www.google.com/search?hl=en&source=hp&biw=1366&bih=515&q=chip+zero+wordpress+theme&aq=f&aqi=&aql=&oq=',

            'ftp://some.domaon.co.uk/',

            'wwwhellocom',

            'tcp://www.domain.org',

            'http://wordpress.org',

            'https:www.secure.net',

            'https://.com',

            'https://www.lock.cc',

            'https://thiscode4u.blogspot.com'

        );

/*
|---------------------
| Let's Check Them
|---------------------
*/

foreach( $urls as $url ) {

    if( get_valid_url( $url ) ) {
        echo "Valid URL: " . $url;
    }

    else {
        echo "Invalid URL: " . $url;
    }

    echo "<br />";

}

Output

Output of above examples will be,

   
Valid URL: https://thiscode4u.blogspot.com

Valid URL: https://thiscode4u.blogspot.comphp-csv-parser-class/#tab-description

Valid URL: http://www.google.com/search?hl=en&source=hp&biw=1366&bih=515&q=chip+zero+wordpress+theme&aq=f&aqi=&aql=&oq=

Valid URL: ftp://some.domaon.co.uk/

Invalid URL: wwwhellocom

Invalid URL: tcp://www.domain.org

Valid URL: http://wordpress.org

Invalid URL: https:www.secure.net

Valid URL: https://.com

Valid URL: https://www.lock.cc

Valid URL: https://thiscode4u.blogspot.com


Friday, 5 June 2015

PHP: Check that characters in a variable are alpha numeric using ereg

<?php
// Example 1
$text = "onlyalphanumericcharacters012345";
if (ereg('[^A-Za-z0-9]', $text))

      echo "This contains characters other than letters and numbers";
}
else { 
       echo "This contains only letters and numbers";   
}

// Example 2
$text = "mixedcharacters012345&../@";
if (ereg('[^A-Za-z0-9]', $text))
{
     echo "This contains characters other than letters and numbers";
}
else {
     echo "This contains only letters and numbers";   
}
?>

PHP: Check number of characters in a range

<?php

//check the amount of characters in a string function

Function CheckNoChars($strText){
//check for between 6 and 12 characters
if (eregi("^.{6,12}$" , $strText))
return true;
else
return false;
}

?>

<?php

//test the function
$str1 = "mypasswordistoolong";
if (CheckNoChars($str1))

//if its OK display this message
echo "this has the correct number of characters";

//if its not OK display this one instead
else
echo "incorrect number of characters";

?>

Wednesday, 3 June 2015

Remove Last Character from String in PHP

This is a very common PHP question of HOW TO remove last character from string in PHP. Find below some ways how to delete last character from string in PHP.
    <?php 
    // method 1 - substr and mb_substr
    substr($string, 0, -1);
    mb_substr($string, 0, -1);
     
    // method 2 - substr_replace
    substr_replace($string, '', -1);
     
    // method 3 - rtrim
    // it trims all specified characters from end of the string
    rtrim($string, ".");
    ?>

Tuesday, 2 June 2015

PHP: Length validator Validates the length of a string

<?php 
function validateLength($string, $minlength=5, $maxlength=30) {
 if (strlen($string) >= $minlength && strlen($string) <= $maxlength) 
return true;
 return false; 
 } 
?>


Usage


$string - (str) the string you wish to validate.

$minlength - (int) set to 0 for no minimum length.

$maxlength - (int) sets the maximum valid length of the string




Boolean return

Friday, 3 October 2014

is_string in PHP

is_string — Find whether the type of a variable is string

Syntax: 
bool is_string ( mixed $var )

Finds whether the type given variable is string.
Parameters: 

var

    The variable being evaluated.

Return Values:

Returns TRUE if var is of type string, FALSE otherwise.
Examples:

Example #1 is_string() example
<?php
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
    echo "is_string(";
    var_export($value);
    echo ") = ";
    echo var_dump(is_string($value));
}
?>

The above example will output:

is_string(false) = bool(false)
is_string(true) = bool(false)
is_string(NULL) = bool(false)
is_string('abc') = bool(true)
is_string('23') = bool(true)
is_string(23) = bool(false)
is_string('23.5') = bool(true)
is_string(23.5) = bool(false)
is_string('') = bool(true)
is_string(' ') = bool(true)
is_string('0') = bool(true)
is_string(0) = bool(false)

Monday, 29 September 2014

wordwrap in PHP

PHP strtok() function is utilized to split a string into smaller strings(tokens).

Syntax:

strtok(string,split)
string : Required. Specifies the string to split

split : Required. Specifies the string characters token delimiters.

Example:

<?php
$str_name = "Good morning. Have a nice day.";
$token_name = strtok($str_name," ");
while($token_name != false){
     echo "$token_name <br />";
     $token_name = strtok(" ");
}
?>
Output will be:
Good
morning.
Have
a
nice
day.
*****************************************************************
 PHP strtolower() function returns an all-lowercase string, regardless of whether the original was all uppercase or mixed.

Syntax:

strtolower(string)
string : Required. Specifies the input string.

Example:

<?php
echo strtolower("Good Morning World!");
?>
Output will be:
good morning world!
*****************************************************************
PHP strtoupper() function returns an all-uppercase string, regardless of whether the original was all lowercase or mixed.

 Syntax:

strtoupper(string)
Example:

<?php
 echo strtoupper("Good Morning World!");
?>
Output will be:
GOOD MORNING WORLD!
*****************************************************************
PHP strtr() function is utilized to interpret certain characters in a string.

Syntax:

strtr(string,from,to)
Or

strtr(string,array)
string : Required. Specifies the string to interpret.

from : Required (unless array is utilized). Holds characters to be translated.

to : Required (unless array is utilized). Holds characters to be translated with.

array : Required (to and from is used). An array holding what to change from as key, and what to change to as value.

Note : If from and to are different length, both will be formatted to the length of the shortest.

Example:

<?php
echo strtr("Hoad Marning","Ha","Go");
$arr_name = array("Good" => "Good", "Morning" => "Night");
echo strtr("Good Morning",$arr_name);
?>
Output will be:
Good Morning
Good Night
*****************************************************************
PHP substr() function is utilized to get a part of a string from a string, beginning at a specified position.

Syntax:

substr(string,start,length)
string : Required.  Specifies the string to return a part of

start : Required.Specifies where to begin in the string.

A positive number – begin at a specified position in the string.
A negative number – begin  at a specified position from the end of the string.
 0 – begin  at the first character in string.
length : Optional. Specifies the length of the returned string. Default is to end of the string.

A positive number – The length to be returned from the start parameter.
 Negative number – he length to be returned from the finish of the string
Note: If begin is a negative number and length is less than or equal to begin, length gets 0.

Example:

<?php
$input_str  = "Good Morning!";
echo substr($input_str,5);
echo substr($input_str,5,7);
?>
Output will be:
Morning!
Morning
*****************************************************************
PHP substr_compare() function is utilized to analyze two strings from a specified starting position.

Function Returns :

 0 – If the two strings are equal
 <0 – If the string1 (from startpos) is less than string2
>0 – If the string1 (from startpos) is greater than string2
Syntax:

substr_compare(string1,string2,startpos,length,case)
string1 : Required. Specifies the first string being compared

string2 : Required. Specifies the second string being compared

startpos : Required. Specifies where to begin comparing in string1

length : Optional. Specifies how much of string1 to compare

case : Optional. Specifies whether or not to perform a case-sensitive compare. Default is FALSE (case-sensitive)

Tip : PHP substr_compare() function is binary safe and alternatively case-sensitive.

Example:

<?php
$input_str  = "Good Morning!";
echo substr_compare($input_str,"Good Morning!",0)."<br />";
echo substr_compare($input_str,"Morning!",5)."<br />";
echo substr_compare($input_str,"MORNING!",5,TRUE);
?>
Output will be:
0
0
0
*****************************************************************
 PHP substr_count() function will count the number of times a substring is found in a string.

Syntax:

substr_count(string,substring,start,length)
string : Required. Specifies the string to check

substring : Required. Specifies the string to search for

start : Optional. Specifies where to in string to begin searching

length : Optional. Specifies the length of the search

Example:

<?php
$input_str  = "Good morning. Have a nice day!";
echo substr_count($input_str,"nice");
?>
Output will be:
1
*****************************************************************
PHP substr_replace() function is utilized to swap a part of a string with another string or words.

Syntax:

substr_replace(string,replacement,start,length)
string : Required. Specifies the string to operate

replacement : Required. Specifies the string to replace

start : Required. Specifies where to start position of the substring to replace

A positive number – Start replacing at the specified position in the string
A negative number – Start replacing at the specified position from the end of the string
0 – Start replacing at the first character in string
 length : Optional. Specifies the length of the string segment to be replaced. Default is the same length as the string.

A positive number – The length of string to be replaced
Negative number – How many characters should be left at end of the string after replacing
0 – Insert instead of replace
Note : If begin is a negative number and length is less than or equivalent to begin, length gets 0.

Example:

<?php
$input_str  = "Good Morning!";
echo substr_replace($input_str,"Night",5);
?>
Output will be:
Good Night!
*****************************************************************
PHP trim() function is utilized to strip out white space (or different characters) from the beginning and end of a string.

Syntax:

trim(string, charlist)
string : Required. Specifies the string to check

charlist : Optional. Specifies which character to remove from the string.

If not specified all of the following characters will be removed :

"\0" – NULL
"\t" – tab
"\n" – new line
"\x0B" – vertical tab
"\r" – carriage return
" " – ordinary white space
Example:

<?php
$input_str= "\n\rGood Morning!\n\r";
echo "Without trim : ". $input_str;
echo "<br />";
echo "With trim : ". trim($input_str);
?>
Output will be:
Without trim : Good Morning!
 With trim : Good Morning!
If You Select "View Source" in the browser window, you will see the following HTML :

<html>
<body>
Without trim : 

Good Morning!

<br />With trim : Good Morning!
</body>
</html>
*****************************************************************
PHP ucfirst() function is capitalizes only the first letter of a string.

Syntax:

ucfirst(string)
string : Required. Specifies the string to convert

Example:

<?php
$input_str  = "good morning!";
echo ucfirst($input_str);
?>
Output will be:
Good morning!
*****************************************************************
PHP ucwords() function is capitalizes the first letter of each word in a string.

Syntax:

ucwords(string)
string : Required. Specifies the string to convert

Example:

<?php
$input_str  = "good morning!";
echo ucwords($input_str);
?>
Output will be:
Good Morning!
*****************************************************************
PHP vfprintf() function is used to write a formatted string to a specified output stream.

PHP vfprintf() function returns the length of the written string.

Syntax:

vfprintf(stream,format,argarray)
stream : Required. Specifies where to write/output the string

format : Required. Specifies the string and how to format the variables in it.

Possible format values:

%% - Returns a percent sign
%b - Binary number
%c - The character according to the ASCII value
%d - Signed decimal number
%e - Scientific notation (e.g. 1.2e+2)
%u - Unsigned decimal number
%f - Floating-point number (local settings aware)
%F - Floating-point number (not local settings aware)
%o - Octal number
%s - String
%x - Hexadecimal number (lowercase letters)
%X - Hexadecimal number (uppercase letters)
Additional format values. These are placed between the % and the letter (example %.2f) :

+ (Forces both + and - in front of numbers. By default, only negative numbers are marked)
' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding)
- (Left-justifies the variable value)
[0-9] (Specifies the minimum width held of to the variable value)
.[0-9] (Specifies the number of decimal digits or maximum string length)

Note : If multiple additional format values are used, they must be in the same order as above.
argarray : Required. An array with arguments to be inserted at the % signs in the format string.

Note : If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and "\$".

Tip : Related functions: fprintf(), printf(), sprintf(), vprintf(), and vsprintf().

Example:

<?php 
$input_str = "Good";
$input_number = 330;
$file_name = fopen("test.txt","w");
echo vfprintf($file_name,"%s Morning. It is day number %u",array($input_str,$input_number));
?>
Output will be:
34
The following text will be written to the file "test.txt":

Good Morning. It is day number 330
*****************************************************************
PHP vprintf () function is utilized to display array values as a formatted string.
The PHP vprintf () function Operates as printf() but accepts an array of arguments, instead of a variable number of arguments.

Syntax:

vprintf(stream,format,argarray)
stream : Required. Specifies where to write/output the string

format : Required. Specifies the string and how to format the variables in it.

Possible format values:

%% - Returns a percent sign
%b - Binary number
%c - The character according to the ASCII value
%d - Signed decimal number
%e - Scientific notation (e.g. 1.2e+2)
%u - Unsigned decimal number
%f - Floating-point number (local settings aware)
%F - Floating-point number (not local settings aware)
%o - Octal number
%s - String
%x - Hexadecimal number (lowercase letters)
%X - Hexadecimal number (uppercase letters)
Additional format values. These are put between the % and the letter (example %.2f) :

+ (Forces both + and -before numbers. By default, just negative numbers are marked)
'(Specifies what to utilize as padding. Default is space. Must be utilized together with the width specifier. Illustration: %'x20s (this utilization "x" as padding)
-(Left-supports the variable value)
[0-9] (Specifies the minimum width expected of to the variable value)
[0-9] (Specifies the number of decimal digits or most extreme string length)

Note : If multiple additional format values are utilized, they must be in the same request as above.
argarray : Required. An array with arguments to be inserted at the % signs in the format string

Note : If there are more % signs than arguments, you should use placeholders. A placeholder is inserted after the % sign, and consists of the argument number and "\$".

Tip : Related functions: fprintf(), printf(), sprintf(), vfprintf() and vsprintf().

Example:

<?php 
$input_str = "Good";
$input_number = 330;
echo vprintf("%s Morning. It is day number %u",array($input_str,$input_number));
?>
Output will be:
Good Morning. It is day number 330
*****************************************************************
vsprintf () function is utilized to write a formatted string to a variable.

The PHP vsprintf () function Operates as sprintf() but accepts an array of arguments, instead of a variable number of arguments.

Syntax:

vsprintf(stream,format,argarray)
stream : Required. Specifies where to write/output the string

format : Required. Specifies the string and how to format the variables in it.

Possible format values:

%% - Returns a percent sign
%b - Binary number
%c - The character according to the ASCII value
%d - Signed decimal number
%e - Scientific notation (e.g. 1.2e+2)
%u - Unsigned decimal number
%f - Floating-point number (local settings aware)
%F - Floating-point number (not local settings aware)
%o - Octal number
%s - String
%x - Hexadecimal number (lowercase letters)
%X - Hexadecimal number (uppercase letters)
Additional format values. These are placed between the % and the letter (example %.2f) :

+ (Forces both + and - in front of numbers. By default, only negative numbers are marked)
' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding)
- (Left-justifies the variable value)
[0-9] (Specifies the minimum width held of to the variable value)
.[0-9] (Specifies the number of decimal digits or maximum string length)
Note:  If various additional format values are utilized, they must be in the same request as above.
argarray : Required. A array with arguments to be embedded at the % signs in the format string.

Note : If there are more % signs than arguments, you should use placeholders. A placeholder is inserted after the % sign, and consists of the argument number and "\$".

Tip : Related functions: fprintf(), printf(), sprintf(), vfprintf(), and vprintf().

Example:

<?php 
$input_str = "Good";
$input_number = 330;
$res_txt = vsprintf($file_name,"%s Morning. It is day number %u",array($input_str,$input_number));
echo $res_txt;
?>
Output will be:
Good Morning. It is day number 330
*****************************************************************
PHP wordwrap() function is utilized to wraps a sentence into new lines using a string break character.

Syntax:

wordwrap(string,width,break,cut)
string : Required. Specifies the string to split into lines.

width : Optional. Specifies the greatest line width. Default is 75.

break : Optional. Specifies the characters to utilize as break. Default is "\n".

cut : Optional. Specifies if statements longer than the specified width should be wrapped. Default is FALSE (no-wrap).

Note : PHP wordwrap function may leave white spaces at the starting of a line.

Example:

<?php
$str = "Welcome to online php guide.";
$newtext= wordwrap($str,22,"<br />\n");
echo $newtext;
?>
Output will be:
Welcome to online php
guide.
*****************************************************************