Manipulating Strings with PHP

Manipulating Strings with PHP
PHP provides many functions that will transform a string argument, subtly or radically, as you’ll soon see.

آموزش آسان و ساده برنامه نویسی یا کد نویسی طراحی سایت بصورت خصوصی و کاربردی

ارایه درگاه پرداخت ePayBank.ir برای برنامه نویسی آسان درگاه اینترنتی پرداخت کارتی شتاب

تبلیغات نیازمندی آنلاین خویش را میتوانید در سایت آگهی MyCityAd.ir درج آگهی نمایید.

Cleaning Up a String with trim(), ltrim(), and strip_tags()
When you acquire text from user input or an external file, you can’t always be sure that you haven’t also picked up white space at the beginning and end of your data.

The trim() function shaves any white space characters, including newlines, tabs, and spaces, from both the start and end of a string. It accepts the string to be modified, returning the cleaned-up version. For example:

<?php
$text = “\t\tlots of room to breathe “;
echo “<pre>$text</pre>”;
// prints ” lots of room to breathe “;
$text = trim($text);
echo “<pre>$text</pre>”;
// prints “lots of room to breathe”;
?>

Of course this might be more work than you require. You might want to keep white space at the beginning of a string but remove it from the end. You can use PHP’s rtrim() function exactly the same as you would use trim(). Only white space at the end of the string argument will be removed, however:

<?php
$text = “\t\tlots of room to breathe “;
echo “<pre>$text</pre>”;
// prints ” lots of room to breathe “;
$text = rtrim($text);
echo “<pre>$text</pre>”;
// prints ” lots of room to breathe”;
?>

PHP provides the ltrim() function to strip white space only from the beginning of a string. Once again, this is called with the string you want to transform and returns a new string, shorn of tabs, newlines, and spaces:

<?php
$text = “\t\tlots of room to breathe “;
echo “<pre>$text</pre>”;
// prints ” lots of room to breathe “;
$text = ltrim($text);
echo “<pre>$text</pre>”;
// prints “lots of room to breathe “;
?>

It is not unusual to have to remove tags from a block of text to display it without any HTML formatting. PHP provides the strip_tags() function for this purpose. The strip_tags() function accepts two arguments: the text to transform and an optional set of HTML tags that strip_tags() can leave in place. The tags in this list should not be separated by any characters.

<?php
$string = “<p>\”I <i>simply</i> will not have it,\” <br/>said Mr Dean.</p>
<p><b>The end.</b></p>”;
echo strip_tags($string, “<br/><p>”);
?>

In the previous code fragment, we create an HTML-formatted string. When we call strip_tags(), we pass it the $string variable and a list of exceptions. The result is that the <p> and <br> tags are left in place and all other tags are stripped out. Also, the matching tag for <p></p>is removed as well.

The output of this snippet is

“I simply will not have it,”
said Mr Dean.

The end.

Note that the italics and bold formatting are gone, but the paragraphs and line breaks remain.

Replacing a Portion of a String Using substr_replace()
The substr_replace() function works similarly to the substr() function, except it allows you to replace the portion of the string that you extract. The function requires three arguments: the string you are transforming, the text you want to add to it, and the starting index. It also accepts an optional length argument. The substr_replace() function finds the portion of a string specified by the starting index and length arguments, replaces this portion with the string provided, and returns the entire transformed string.

In the following code fragment used to renew a user’s membership code, we change its second two characters:

<?php
$membership = “mz05xyz”;
$membership = substr_replace($membership, “06″, 2, 2);
echo “New membership number: $membership”;
// prints “New membership number: mz06xyz”
?>

The result of this code is that the old membership number, “mz05xyz”, is transformed into the new membership number, “mz06xyz”.

Replacing Substrings Using str_replace
The str_replace() function is used to replace all instances of a given string within another string. It requires three arguments: a search string, the replacement string, and the master string. The function returns the transformed string.

The following example uses str_replace() to change all references from 2005 to 2006 within a master string:

<?php
$string = “<h1>The 2005 Guide to All Things Good in the World</h1>”;
$string .= “<p>Site contents copyright 2005.</p>”;
echo str_replace(“2005″,”2006″,$string);
?>

The str_replace() function accepts arrays as well as strings for all of its arguments. This allows us to perform multiple search and replace operations on a subject string, and even on more than one subject string. Take the following snippet, for instance:

<?php
$source = array(
“The package which is at version 4.2 was released in 2005.”,
“The year 2005 was an excellent time for PointyThing 4.2!”);
$search = array(“4.2″, “2005″);
$replace = array(“5.3″, “2006″);
$source = str_replace($search, $replace, $source);
foreach($source as $str) {
echo “$str<br>”;
}
?>

The output of this snippet is

The package which is at version 5.3 was released in 2006.
The year 2006 was an excellent time for PointyThing 5.3!

When an array of strings is passed to str_replace() for its first and second arguments, it attempts to switch each search string with its corresponding replace string in the text to be transformed. When the third argument is an array, the str_replace() function returns an array of strings. The search and replace operation will have been executed upon each string in the array.

Converting Case
PHP provides several functions that allow you to convert the case of a string. Changing case is often useful for string comparisons. To get an uppercase version of a string, use the function strtoupper(). This function requires only the string that you want to convert and returns the converted string:

<?php
$membership = “mz06xyz”;
$membership = strtoupper($membership);
echo “$membership”; // prints “MZ06XYZ”
?>

To convert a string to lowercase characters, use the strtolower() function. Once again, this function requires the string you want to convert and returns a converted version:

<?php
$membership = “MZ06XYZ”;
$membership = strtolower($membership);
echo “$membership”; // prints “mz06xyz”
?>

PHP also provides a case function that has a useful cosmetic purpose. The ucwords() function makes the first letter of every word in a string uppercase. In the following fragment, we make the first letter of every word in a user-submitted string uppercase:

<?php
$full_name = “violet elizabeth bott”;
$full_name = ucwords($full_name);
echo $full_name; // prints “Violet Elizabeth Bott”
?>

Although this function makes the first letter of each word uppercase, it does not touch any other letters. So, if the user had had problems with her Shift key in the previous example and submitted VIolEt eLIZaBeTH bOTt, our approach would not have done much to fix the string. We would have ended up with VIolEt ELIZaBeTH BOTt, which isn’t much of an improvement. We can deal with this by making the submitted string lowercase with the strtolower() function before invoking ucwords():

<?php
$full_name = “VIolEt eLIZaBeTH bOTt”;
$full_name = ucwords(strtolower($full_name));
echo $full_name; // prints “Violet Elizabeth Bott”
?>

Finally, the ucfirst() function capitalizes only the first letter in a string. In the following fragment, we capitalize the first letter in a user-submitted string:

<?php
$myString = “this is my string.”;
$myString = ucfirst($myString);
echo $myString; // prints “This is my string.”
?>

Working with case-related string functions can prove useful when attempting to authenticate case-insensitive passwords, for example. If the user inputs “MyPass” and the stored password is “mypass” but you want the match to be case-insensitive, you can attempt to match a lowercase (or uppercase) version of the user input with the lowercase (or uppercase) version of the stored password. If they match in their similarly cased format, the user can be authenticated even if he typed something different from what was actually stored.

Wrapping Text with wordwrap() and nl2br()
When you present plain text within a web page, you are often faced with a problem in which new lines are not displayed and your text runs together into one big mess. The nl2br() function conveniently converts every new line into an HTML break. So

<?php
$string = “one line\n”;
$string .= “another line\n”;

$string .= “a third for luck\n”;
echo nl2br($string);
?>

outputs

one line<br />
another line<br />
a third for luck<br />

By the Way

The <br> tags are output in XHTML-compliant format (<br />).

The nl2br() function is great for maintaining newlines that are already in the text you are converting. Occasionally, you may want to add arbitrary line breaks to format a column of text. The wordwrap() function is perfect for this.wordwrap() requires one argument, the string to be transformed. By default, wordwrap() wraps lines every 75 characters and uses \n as its linebreak character. So, the code fragment

<?php
$string = “Given a long line, wordwrap() is useful as a means of “;
$string .= “breaking it into a column and thereby making it easier to read”;
echo wordwrap($string);
?>

would output

Given a long line, wordwrap() is useful as a means of breaking it into a
column and thereby making it easier to read

Because the lines are broken with the character \n, the formatting does not show up in HTML code, of course. The wordwrap() function has two more optional arguments: a number representing the maximum number of characters per line and a string representing the end of line string you want to use. So, applying the function call

echo wordwrap($string, 24, “<br/>\n”);

to our $string variable, our output would be

Given a long line,<br/>
wordwrap() is useful as<br/>
a means of breaking it<br/>
into a column and<br/>
thereby making it easier<br/>
to read

The wordwrap() function won’t automatically break at your line limit if a word has more characters than the limit. You can, however, use an optional fourth argument to enforce this. The argument should be a positive integer. So, using wordwrap() in conjunction with the fourth argument, we can now wrap a string, even where it contains words that extend beyond the limit we are setting. This fragment

<?php
$string = “As usual you will find me at http://www.witteringonaboutit.com/”;
$string .= “chat/eating_green_cheese/forum.php. Hope to see you there!”;
echo wordwrap($string, 24, “<br/>\n”, 1);
?>

outputs

As usual you will find<br/>
me at<br/>

http://www.witteringonab<br/>

outit.com/chat/eating_gr<br/>
een_cheese/forum.php.<br/>
Hope to see you there!

Instead of

As usual you will find<br/>
me at<br/>
http://www.witteringonaboutit.com/chat/eating_green_cheese/forum.php. <br/>
Hope to see you there!

Breaking Strings into Arrays with explode()
The delightfully named explode() function is similar in some ways to strtok(). But explode() breaks up a string into an array, which you can then store, sort, or examine as you want. The explode() function requires two arguments: the delimiter string that you want to use to break up the source string and the source string itself. The function optionally accepts a third argument, which determines the maximum number of pieces the string can be broken into. The delimiter string can include more than one character, all of which form a single delimiter (unlike multiple delimiter characters passed to strtok(), each of which will be a delimiter in its own right). The following fragment breaks up a date and stores the result in an array:

<?php
$start_date = “2006-02-19″;
$date_array = explode(“-”, $start_date);
// $date_array[0] == “2006″
// $date_array[1] == “02″
// $date_array[2] == “19″
echo $date_array[0].”-”.$date_array[1].”-”.$date_array[2];
//prints 2006-02-19
?>

Now that your head is filled with some common PHP string functions, let’s move on to date and time functions.