String Manipulation

A collection of 19 tips on manipulating PHP strings. Clear answers are provided with tutorial exercises on string functions including strlen, trim, substr, chop, strpos, strcmp, split, etc. Topics included in this collection are:

  1. How To Get the Number of Characters in a String?
  2. How To Remove White Spaces from the Beginning and/or the End of a String?
  3. How To Remove the New Line Character from the End of a Text Line?
  4. How To Remove Leading and Trailing Spaces from User Input Values?
  5. How to Find a Substring from a Given String?
  6. What Is the Best Way to Test the strpos() Return Value?
  7. How To Take a Substring from a Given String?
  8. How To Replace a Substring in a Given String?
  9. How To Reformat a Paragraph of Text?
  10. How To Convert Strings to Upper or Lower Cases?
  11. How To Convert the First Character to Upper Case?
  12. How To Compare Two Strings with strcmp()?
  13. How To Convert Strings in Hex Format?
  14. How To Generate a Character from an ASCII Value?
  15. How To Convert a Character to an ASCII Value?
  16. How To Split a String into Pieces?
  17. How To Join Multiple Strings into a Single String?
  18. How To Apply UUEncode to a String?
  19. How To Replace a Group of Characters by Another Group?

How To Get the Number of Characters in a String?

You can use the “strlen()” function to get the number of characters in a string. Here is a PHP script example of strlen():

<?php
print(strlen('It\'s Friday!'));
?>

This script will print:

12

How To Remove White Spaces from the Beginning and/or the End of a String?

There are 4 PHP functions you can use remove white space characters from the beginning and/or the end of a string:

  • trim() – Remove white space characters from the beginning and the end of a string.
  • ltrim() – Remove white space characters from the beginning of a string.
  • rtrim() – Remove white space characters from the end of a string.
  • chop() – Same as rtrim().

White space characters are defined as:

  • ” ” (ASCII 32 (0x20)), an ordinary space.
  • “\t” (ASCII 9 (0x09)), a tab.
  • “\n” (ASCII 10 (0x0A)), a new line (line feed).
  • “\r” (ASCII 13 (0x0D)), a carriage return.
  • “” (ASCII 0 (0x00)), the NULL-byte.
  • “\x0B” (ASCII 11 (0x0B)), a vertical tab.

Here is a PHP script example of trimming strings:

<?php
$text = "\t \t Hello world!\t \t ";
$leftTrimmed = ltrim($text);
$rightTrimmed = rtrim($text);
$bothTrimmed = trim($text);
print("leftTrimmed = ($leftTrimmed)\n");
print("rightTrimmed = ($rightTrimmed)\n");
print("bothTrimmed = ($bothTrimmed)\n");
?>

This script will print:

leftTrimmed = (Hello world!              )
rightTrimmed = (                 Hello world!)
bothTrimmed = (Hello world!)

How To Remove the New Line Character from the End of a Text Line?

If you are using fgets() to read a line from a text file, you may want to use the chop() function to remove the new line character from the end of the line as shown in this PHP script:

<?php
$handle = fopen("/tmp/inputfile.txt", "r");
while ($line=fgets()) {
  $line = chop($line);
  # process $line here...
}
fclose($handle);
?>

How To Remove Leading and Trailing Spaces from User Input Values?

If you are taking input values from users with a Web form, users may enter extra spaces at the beginning and/or the end of the input values. You should always use the trim() function to remove those extra spaces as shown in this PHP script:

<?php
$name = $_REQUEST("name");
$name = trim($name);
# $name is ready to be used...
?>

How to Find a Substring from a Given String?

To find a substring in a given string, you can use the strpos() function. If you call strpos($haystack, $needle), it will try to find the position of the first occurrence of the $needle string in the $haystack string. If found, it will return a non-negative integer represents the position of $needle. Othewise, it will return a Boolean false. Here is a PHP script example of strpos():

<?php $haystack1 = “2349534134345fyicenter16504381640386488129”; $haystack2 = “fyicenter234953413434516504381640386488129”; $haystack3 = “center234953413434516504381640386488129fyi”; $pos1 = strpos($haystack1, “fyicenter”); $pos2 = strpos($haystack2, “fyicenter”); $pos3 = strpos($haystack3, “fyicenter”); print(“pos1 = ($pos1); type is ” . gettype($pos1) . “\n”); print(“pos2 = ($pos2); type is ” . gettype($pos2) . “\n”); print(“pos3 = ($pos3); type is ” . gettype($pos3) . “\n”); ?>

This script will print:

pos1 = (13); type is integer pos2 = (0); type is integer pos3 = (); type is boolean

“pos3” shows strpos() can return a Boolean value.


What Is the Best Way to Test the strpos() Return Value?

Because strpos() could two types of values, Integer and Boolean, you need to be careful about testing the return value. The best way is to use the “Identical(===)” operator. Do not use the “Equal(==)” operator, because it does not differentiate “0” and “false”. Check out this PHP script on how to use strpos():

<?php $haystack = “needle234953413434516504381640386488129”; $pos = strpos($haystack, “needle”); if ($pos==false) { print(“Not found based (==) test\n”); } else { print(“Found based (==) test\n”); } if ($pos===false) { print(“Not found based (===) test\n”); } else { print(“Found based (===) test\n”); } ?>

This script will print:

Not found based (==) test Found based (===) test

Of course, (===) test is correct.


How To Take a Substring from a Given String?

If you know the position of a substring in a given string, you can take the substring out by the substr() function. Here is a PHP script on how to use substr():

<?php $string = “beginning”; print(“Position counted from left: “.substr($string,0,5).”\n”); print(“Position counted form right: “.substr($string,-7,3).”\n”); ?>

This script will print:

Position counted from left: begin Position counted form right: gin

substr() can take negative starting position counted from the end of the string.


How To Replace a Substring in a Given String?

If you know the position of a substring in a given string, you can replace that substring by another string by using the substr_replace() function. Here is a PHP script on how to use substr_replace():

<?php $string = “Warning: System will shutdown in NN minutes!”; $pos = strpos($string, “NN”); print(substr_replace($string, “15”, $pos, 2).”\n”); sleep(10*60); print(substr_replace($string, “5”, $pos, 2).”\n”); ?>

This script will print:

Warning: System will shutdown in 15 minutes! (10 minutes later) Warning: System will shutdown in 5 minutes!

Like substr(), substr_replace() can take negative starting position counted from the end of the string.


How To Reformat a Paragraph of Text?

You can wordwrap() reformat a paragraph of text by wrapping lines with a fixed length. Here is a PHP script on how to use wordwrap():

<?php
$string = "TRADING ON MARGIN POSES ADDITIONAL
RISKS AND IS NOT SUITABLE FOR ALL
        INVESTORS.
A COMPLETE LIST OF THE RISKS ASSOCIATED WITH MARGIN TRADING IS
AVAILABLE IN THE MARGIN RISK DISCLOSURE DOCUMENT.";
$string = str_replace("\n", " ", $string);
$string = str_replace("\r", " ", $string);
print(wordwrap($string, 40)."\n");
?>

This script will print:

TRADING ON MARGIN POSES ADDITIONAL
RISKS AND IS NOT SUITABLE FOR ALL
    INVESTORS.   A COMPLETE LIST OF THE
RISKS ASSOCIATED WITH MARGIN TRADING IS
 AVAILABLE IN THE MARGIN RISK DISCLOSURE
DOCUMENT.

The result is not really good because of the extra space characters. You need to learn preg_replace() to replace them with a single space character.


How To Convert Strings to Upper or Lower Cases?

Converting strings to upper or lower cases are easy. Just use strtoupper() or strtolower() functions. Here is a PHP script on how to use them:

<?php
$string = "PHP string functions are easy to use.";
$lower = strtolower($string);
$upper = strtoupper($string);
print("$lower\n");
print("$upper\n");
print("\n");
?>

This script will print:

php string functions are easy to use.
PHP STRING FUNCTIONS ARE EASY TO USE.

How To Convert the First Character to Upper Case?

If you are processing an article, you may want to capitalize the first character of a sentence by using the ucfirst() function. You may also want to capitalize the first character of every words for the article title by using the ucwords() function. Here is a PHP script on how to use ucfirst() and ucwords():

<?php
$string = "php string functions are easy to use.";
$sentence = ucfirst($string);
$title = ucwords($string);
print("$sentence\n");
print("$title\n");
print("\n");
?>

This script will print:

Php string functions are easy to use.
Php String Functions Are Easy To Use.

How To Compare Two Strings with strcmp()?

PHP supports 3 string comparison operators, <, ==, and >, that generates Boolean values. But if you want to get an integer result by comparing two strings, you can the strcmp() function, which compares two strings based on ASCII values of their characters. Here is a PHP script on how to use strcmp():

<?php
$a = "PHP is a scripting language.";
$b = "PHP is a general-purpose language.";
print('strcmp($a, $b): '.strcmp($a, $b)."\n");
print('strcmp($b, $a): '.strcmp($b, $a)."\n");
print('strcmp($a, $a): '.strcmp($a, $a)."\n");
?>

This script will print:

strcmp($a, $b): 1
strcmp($b, $a): -1

How To Convert Strings in Hex Format?

If you want convert a string into hex format, you can use the bin2hex() function. Here is a PHP script on how to use bin2hex(): <?php $string = “Hello\tworld!\n”; print($string.”\n”); print(bin2hex($string).”\n”); ?> This script will print:

Hello world! 48656c6c6f09776f726c64210a


How To Generate a Character from an ASCII Value?

If you want to generate characters from ASCII values, you can use the chr() function. chr() takes the ASCII value in decimal format and returns the character represented by the ASCII value. chr() complements ord(). Here is a PHP script on how to use chr(): <?php print(chr(72).chr(101).chr(108).chr(108).chr(111).”\n”); print(ord(“H”).”\n”); ?> This script will print:

Hello 72


How To Convert a Character to an ASCII Value?

If you want to convert characters to ASCII values, you can use the ord() function, which takes the first charcter of the specified string, and returns its ASCII value in decimal format. ord() complements chr(). Here is a PHP script on how to use ord(): <?php print(ord(“Hello”).”\n”); print(chr(72).”\n”); ?> This script will print:

72 H


How To Split a String into Pieces?

There are two functions you can use to split a string into pieces:

  • explode(substring, string) – Splitting a string based on a substring. Faster than split().
  • split(pattern, string) – Splitting a string based on a regular expression pattern. Better than explode() in handling complex cases.

Both functions will use the given criteria, substring or pattern, to find the splitting points in the string, break the string into pieces at the splitting points, and return the pieces in an array. Here is a PHP script on how to use explode() and split(): <?php $list = explode(“_”,”php_strting_function.html”); print(“explode() returns:\n”); print_r($list); $list = split(“[_.]”,”php_strting_function.html”); print(“split() returns:\n”); print_r($list); ?>

This script will print:

explode() returns: Array ( [0] => php [1] => strting [2] => function.html ) split() returns: Array ( [0] => php [1] => strting [2] => function [3] => html )

The output shows you the power of power of split() with a regular expression pattern as the splitting criteria. Pattern “[_.]” tells split() to split whenever there is a “_” or “.”.


How To Join Multiple Strings into a Single String?

If you multiple strings stored in an array, you can join them together into a single string with a given delimiter by using the implode() function. Here is a PHP script on how to use implode():

<?php
$date = array('01', '01', '2006');
$keys = array('php', 'string', 'function');
print("A formated date: ".implode("/",$date)."\n");
print("A keyword list: ".implode(", ",$keys)."\n");
?>

This script will print:

A formated date: 01/01/2006
A keyword list: php, string, function

How To Apply UUEncode to a String?

UUEncode (Unix-to-Unix Encoding) is a simple algorithm to convert a string of any characters into a string of printable characters. UUEncode is reversible. The reverse algorithm is called UUDecode. PHP offeres two functions for you to UUEncode or UUDecode a string: convert_uuencode() and convert_uudecode(), Here is a PHP script on how to use them:

<?php
$msgRaw = "
From\tTo\tSubject
Joe\tLee\tHello
Dan\tKia\tGreeting";
$msgEncoded = convert_uuencode($msgRaw);
$msgDecoded = convert_uudecode($msgEncoded);
if ($msgRaw === $msgDecoded) {
  print("Conversion OK\n");
  print("UUEncoded message:\n");
  print("-->$msgEncoded<--\n");
  print("UUDecoded message:\n");
  print("-->$msgDecoded<--\n");
} else {
  print("Conversion not OK:\n");
}
?>

This script will print:

Conversion OK
UUEncoded message:
-->M1G)O;0E4;PE3=6)J96-T#0I*;V4)3&5E"4AE;&QO#0I$86X)2VEA"4=R965T
#:6YG
`
<--
UUDecoded message:
-->
From    To      Subject
Joe     Lee     Hello
Dan     Kia     Greeting<--

The output shows you that the UUEncode string is a multiple-line string with a special end-of-string mark \x20.


How To Replace a Group of Characters by Another Group?

While processing a string, you may want to replace a group of special characters with some other characters. For example, if you don’t want to show user’s email addresses in the original format to stop email spammer collecting real email addresses, you can replace the “@” and “.” with something else. PHP offers the strtr() function with two format to help you:

  • strtr(string, from, to) – Replacing each character in “from” with the corresponding character in “to”.
  • strtr(string, map) – Replacing each substring in “map” with the corresponding substring in “map”.

Here is a PHP script on how to use strtr():

<?php
$email = "joe@dev.fyicenter.moc";
$map = array("@" => " at ", "." => " dot ");
print("Original: $email\n");
print("Character replacement: ".strtr($email, "@.", "#_")."\n");
print("Substring replacement: ".strtr($email, $map)."\n");
?>

This script will print:

Original: joe@dev.fyicenter.moc
Character replacement: joe#dev_fyicenter_moc
Substring replacement: joe at dev dot fyicenter dot moc

To help you to remember the function name, strtr(), “tr” stands for “translation”.

strcmp($a, $a): 0

As you can see, strcmp() returns 3 possible values:

  • 1: The first string is greater than the section string.
  • -1: The first string is less than the section string.
  • 0: The first string is equal to the section string.
Advertisements

3 Comments

  1. vinod said,

    July 8, 2008 at 12:08 am

    really these string manipulation super

  2. January 22, 2009 at 4:45 am

    […] – bookmarked by 6 members originally found by chaserpaul on 2008-12-29 String Manipulation https://scvinodkumar.wordpress.com/2008/07/05/string-manipulation/ – bookmarked by 3 members […]

  3. ayquxuem said,

    May 17, 2010 at 2:10 am

    yEuStO djwaajhsqfcl, [url=http://eeasggyeoyib.com/]eeasggyeoyib[/url], [link=http://cypptsfyptzq.com/]cypptsfyptzq[/link], http://ectiwlndqfac.com/


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: