14 Strings with PHP

Hiren Joshi

epgp books

 

 

Strings

 

As the HTML form submitted data received by server as string, string is an important part of PHP application. Strings can be used single quotes or double quotes. When string is created using double quotes, then PHP engine perform variable substitution. Variable substitution means variable name is replace by the variable value. When variable name is replace by variable value at that if necessary PHP converts the variable value into string. The conversion of variable value into string is known as interpolation.

 

Let us understand it by an example.

$count = 3;

$item = “Ice Cream”;

$msg1 = “I have $count $item.”;

$msg2 = “I have $count $items.”;

$msg3 = “I have $count $item s.”;

$msg4 = “I have $count ${item}s.”;

echo “<br> Message 1 : $msg1”;

echo “<br> Message 2 : $msg2”;

echo “<br> Message 3 : $msg3”;

echo “<br> Message 4 : $msg4”;

 

The curly braces { } is used to separate variable name with text shown  in $msg4.

 

Escape Sequence with String

 

The escape sequence behave differently for single quote and double quotes.

The \    (read as back slash) works for single quote and double quotes.

 

For example:

 

$dir1 = ‘H:\wamp\www\PGWAD’;

echo “<br> $dir1”;

$dir2 = ‘H:\\wamp\\www\\PGWAD’;

echo “<br> $dir2”;

 

$music = ‘Meet \’s Music Store’;

echo “<br> $music”;

 

$newmusic = “Meet’s Music Store”;

echo “<br> $newmusic”;

 

$demo = “He said it costs $12”;

echo “<br> $demo”;

 

Then the output for the following is:

    H:\wamp\www\PGWAD

H:\wamp\www\PGWAD

Meet ‘s Music Store

Meet’s Music Store

He said it costs $12

 

In-Built useful String Functions

 

PHP provides many built in functions. Below is the list of various types of string functions provided by PHP.

  • Function for working with string length
  • Functions that search a string
  • Functions that replace part of a string
  • Functions that modify the strings
  • Functions that convert between strings and arrays
  • Functions that convert between strings and ASCII integer values
  • Functions for compare two strings

 

Functions for working with string length and substrings

 

Function Description
empty($str) Returns true if $str is empty(“”), a Null Value or “0”.
strlen($str) Retruns the length of the string $str.
substr($str, $i[, $len])

 

 

 

Retruns substring from the string $str. $i is used to make start

position for substring $str. $len is used to determine length. If

$len is omitted, then the string starts from $i to the end of the

string $str. The first character is at 0th position.

 

<?php

//empty

$phone = 9876543210;

if(empty($phone))

{

echo “<br> phone is not set”;

}

else

{

echo “<br> phone is set: $phone”;

}

//strlen

$str = “Hiren Joshi”;

$len = strlen($str);

echo “<br> The length of string $str is :$len”;

//substr

$sub = substr($str,6,5);

echo “<br> The substring of $str is $sub”;

?>

 

The output will be:

 

phone is set: 9876543210

The length of string Hiren Joshi is :11

The substring of Hiren Joshi is Joshi

 

Functions that search a string

 

Function Description
Strpos($str1, $str2 [,$offset])

 

 

 

Search  the first occurrence of $str2 in $str1. If found then

returns integer number of the first occurrence.  The optional

$offset helps to determine start position for occurrence of $str1

in $str1.

Stripos($str1, $str2 [,$offset]) Case in-sensitive version of strops function.
Strrpos($str1, $str2 [,$offset])

 

Same as strops except it statrt searching from the end of the

string to the start of the string.

Strtipos($str1, $str2 [,$offset]) Case in-sensitive version of strrpos function.

 

 

<?php

//strpos

$str = “Hiren Joshi”;

$pos = strpos($str,’h’);

echo “<br> character h is found at position (strpos): $pos”; //stripos

$ipos = stripos($str,’h’);

echo “<br> character h is found at position (stripos): $ipos”; //strrpos

$rpos = strrpos($str,’h’);

echo “<br> character h is found at position (strrpos): $rpos”; //strripos

$ripos = strripos($str,’h’);

echo “<br> character h is found at position(strripos): $ripos”; //offset

$without = stripos($str,”h”);

echo “<br> character h is found at position( without offset strripos): $without”; $offset = stripos($str,”h”,1);

echo “<br> character h is found at position( with offset strripos): $offset”; ?>

 

The output will be:

 

character h is found at position (strpos): 9

character h is found at position (stripos): 0

character h is found at position (strrpos): 9

character h is found at position(strripos): 9

character h is found at position( without offset strripos): 0

character h is found at position( with offset strripos): 9

 

Functions that replace part of a string

 

Function Description
str_replace($str1, $new, $str2) Return a new string which replace $str with $new in $str2.
str_ireplace($str1, $new, $str2) Case-insensitive version of str_replace function.

 

 

<?php

$str = “Hello Rohit”;

$ans =str_replace(“Hello”,”Hi!”,$str);

echo “<br> Original string is $str <br> replaced with $ans”; $irep = str_ireplace(“r”,”M”,$str);

echo “<br> Original string is $str <br> replaced with $irep”; ?>

 

Program output is:

 

Original string is Hello Rohit

replaced with Hi! Rohit

Original string is Hello Rohit

replaced with Hello Mohit

 

Functions that modify the strings

 

Function Description
ltrim($str)

 

Return a new string which trimmed white spaces from the left

side of the $str.

rtrim($str)

 

Return a new string which trimmed white spaces from the right

side of the $str.

trim($str)

 

Returns a new string which trimmed white spaces from the left

and right side of the $str.

str_pad($str, $len, [,$pad [,$type] ])

 

 

 

 

Returns a new string which padded  the string $string upto the

length $len. By default the $pad is space, but you can specify any

other character. The padding is by default right. You can select

left, right or both for $type by setting the constant

STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH

lcfirst($str) Returns a new string which converts the first letter to lowercase.
ucfirst($str) Returns a new string which converts the first letter to uppercase.
ucwords($str)

 

Returns a new string which converts the first letter of each word

to uppercase.

strtolower($str)

 

Returns a new string which converted all the letters of input string

$str into lower case.

strtoupper($str)

 

Returns a new string which converted  all the letters of input

string $str into upper case.

strrev($str) Returns a new string in which the sequence of letters is reversed.
str_shuffle($str)

 

Returns a new string which shuffle the letters in the string $str

randomly.

str_repeat($str, $i) Returns a new string in which string $str is repeated $i times.

 

 

<?php

$name = ‘ Sunday is a holiday ‘;

$olen = strlen($name);

$ltrim = ltrim($name); //ltrim

$lltrim = strlen($ltrim);

echo “<br> Original Length of the string $name is : $olen <br> After left-side trimming: $lltrim”;

echo “<br> Original string after left-trimming is : $ltrim”; $rtrim = rtrim($name); //rtrim $rtrim = strlen($rtrim);

echo “<br> Original Length of the string $name is : $olen <br> After right-side trimming: $rtrim”;

$trim = trim($name); //trim

$trimlen = strlen($trim);

echo “<br> Original Length of the string $name is : $olen <br> After both side trimming: $trimlen”; $str = “Virat Kohli”;

$ans = str_pad($str,25,’*’,STR_PAD_BOTH); //str_pad echo “<br> After both side padding it is:$ans”; $virat = ‘Virat Kohli’;

$lcfirst = lcfirst($virat); //lcfirst

echo “<br> Original : $virat and <br> after lcfirst it is: $lcfirst”; $sachin = ‘sachin Tendulkar’;

$ucfirst = ucfirst($sachin); //ucfirst

echo “<br> Original : $sachin and <br> after ucfisrst it is: $ucfirst”; $viru = ‘virendra sehwag’;

$ucwords = ucwords($name); //ucwords

echo “<br> Original : $viru and <br> after ucwords it is: $ucwords”; $caps = ‘ALL CAPS’;

$strtolower = strtolower($caps); //strtolower

echo “<br> Original : $caps and <br> after strtolower it is: $strtolower”; $small = ‘small case letters’;

$strtoupper = strtoupper($small); //strtoupper

echo “<br> Original : $small and <br> after strtoupper it is: $strtoupper”;

$city = ‘Ahmedabad’;

$strrev = strrev($city); //strrev

echo “<br> Original string is: $city and <br> after strrev it is: $strrev”;

$str = ‘string’;

$shuffle = str_shuffle($str);

echo “<br> Original string is: $str and <br> after shuffle it is: $shuffle”;

$strrepeat = str_repeat($str,4); //str_repeat

echo “<br> Original string is: $str and <br> after repeat it 4 times : $strrepeat”;?>

 

Then the output will be:

 

Original Length of the string Sunday is a holiday is : 22

After left-side trimming: 20

Original string after left-trimming is : Sunday is a holiday

Original Length of the string Sunday is a holiday is : 22

After right-side trimming: 21

Original Length of the string Sunday is a holiday is : 22

After both side trimming: 19

After both side padding it is:*******Virat Kohli*******

Original : Virat Kohli and

after lcfirst it is: virat Kohli

Original : sachin Tendulkar and

after ucfisrst it is: Sachin Tendulkar

Original : virendra sehwag and

after ucwords it is: Sunday Is A Holiday

Original : ALL CAPS and

after strtolower it is: all caps

Original : small case letters and

after strtoupper it is: SMALL CASE LETTERS

Original string is: Ahmedabad and

after strrev it is: dabademhA

Original string is: string and

after shuffle it is: ringts

Original string is: string and

after repeat it 4 times : stringstringstringstring

 

Functions that convert between strings and arrays

 

Function Description
explode($sep, $str)

 

 

 

Returns an array of string which are separated in

$str by delimeter $sep. The delimeter $sep can be

any length. If $str is an empty string, each string in

an array consist of single letter.

implode($sep, $sa)

 

Returns a string that results from joining the

elements of array $sa with the $sep string.

 

 

<?php

//explode

$email = ‘abc.def@ghi.com,jkl.mno@pqr.com,stu.uvw@xyz.com’; $e = explode(‘,’,$email);

echo “<br> After explode the emails are :”;

foreach($e as $v)

{

echo “<br> $v”;

}

//implode

$i = implode(‘|’,$e);

echo “<br> After emplode the elements of email array becomes a string:”;

echo “<br> $i”;

?>

 

The output will be:

 

After explode the emails are :

abc.def@ghi.com

jkl.mno@pqr.com

stu.uvw@xyz.com

    After implode the elements of email array becomes a string:

abc.def@ghi.com|jkl.mno@pqr.com|stu.uvw@xyz.com

 

Functions that convert between strings and ascii integer values

 

Function Description
chr($val) Return a string which to ASCII character of input value
ord($string) Return a string convert to ASCII value of input string

 

 

<?php

$chr = chr(72);

echo “<br> The ASCII character for value 72 is: $chr”; $ord = ord(‘H’);

echo “<br> The integer value for the character H is: $ord”; ?>

 

The output is:

 

The ASCII character for value 72 is: H

The integer value for the character H is: 72

 

Functions for compare two strings

 

Function Description
strcmp($str1, $str2)

 

 

 

 

 

 

It compares two strings and return an integer value which

specifies their sequence. If the function returns

-1: $str1 comes before $str2

1:$str1 comes after $str2

0:$str1 and $str2 are the same

This  comparison  is  case  sensitive.  Hence  Capital  letter

comes before small case letters.

strcasecmp($str1, $str2) Case-insensitive version of strcmp function
strnatcmp($str1,$str2)

 

 

Same  as  strcmp  function.  The  only  difference  is  that  the

function makes “natural” comparison for numbers of   $str1

and $str2

strnatcasecmp($str1, $str2) Case-insensitive version of strnatcmp function.

 

 

<?php

$result1 = strcmp(‘Anand’,’Zarna’);

echo “<br> $result1”;

$result2 = strcmp(‘Anand’,’zarna’);

echo “<br> $result2”;

$result3 = strcasecmp(‘Anand’,’zarna’);

echo “<br> $result3”;

$result4 = strcmp(‘img03′,’img10’);

echo “<br> $result4”;

$result5 = strcmp(‘img3′,’img10’);

echo “<br> $result5”;

$result6 = strnatcmp(‘img3′,’img10’);

echo “<br> $result6”;

?>

 

The output will be:

 

-1

-1

-25

-1

1

-1

 

You can find many strings functions at

 

http://www.php.net/manual/en/ref.strings.php

you can view video on Strings with PHP

References:

 

1. Luke Welling, Laura Thomson: PHP and MySQL Web Development, Pearson,

2. W. Jason Gilmore: Beginning PHP and MySQL 5 From Novice to Professional, Apress

3. Elizabeth Naramore, Jason Gerner, Yann Le Scouarnec, Jeremy Stolz, Michael K. Glass:Beginning PHP5, Apache, and MySQL Web Development, Wrox,

4. Robin Nixon: Learning PHP, MySQL, and JavaScript, O’Reilly Media

5. Ed Lecky-Thompson, Heow Eide-Goodman, Steven D. Nowicki, Alec Cove: Professional PHP,Wrox

6. Tim Converse, Joyce Park, Clark Morgan: PHP5 and MySQL Bible

7. Joel Murach, Ray Harris: Murach’s PHP and MySQL, Shroff/Murach

8. Ivan Bayross, Web Enabled Commercial Application Development Using HTML/Javascript/DHTML/PHP , BPB Publications

9. Julie C. Meloni, Sams Teach Yourself PHP, MySQL and Apache All in One, Sams

10. Larry Ullman, PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide, Pearson Education

11. http://www.php.net

12. http://www.w3schools.com/

13. http://www.tutorialspoint.com/