(click anywhere to close)
OPEN MENU

[PHP] Strings II

category: Website | course: PHP | difficulty:

I think a practical example is in order here – all this theoretical talk about numbers and strings might start to feel a bit useless at the moment, and the last thing I want you to do is quit learning!

On this website, there’s lots of things going on. When you access a page, it takes the URL (which is a string), and chops it up into little pieces. Based on those, it finds the article that belongs with it, and loads that post (which is one huge string) from the database. I don’t like writing large bits of HTML to insert code examples, images, or other special things – so I use a much easier system. I simply invented my own special tags (such as [more] or #LINKHERE#), and I replace those tags by their complex HTML counterparts, to create a page that is dynamically created when you load it! It saves me work, it saves you work.

This, is the power of strings. We can extract all sorts of information from them, and without them, PHP and the world wide web would probably not exist. This chapter will discuss the most fundamental functions you can call on strings to make them dance.

Changing Case

Let’s start simple. Sometimes you have a string where the letters are lowercase, where they should be uppercase (or vice versa). To change case, we have these functions:

Function

Description

lcfirst($str)

Makes the first character of the string lowercase

ucfirst($str)

Makes the first character of the string uppercase

strtolower($str)

Makes all characters of the string lowercase

strtoupper($str)

Makes all characters of the string uppercase

$mail_goodbye = "kiND reGArdS, PANDaqi";

//Let's fix this ugly sentence by making it all lowercase,
//and the first letter uppercase
echo ucfirst(strtolower($mail_goodbye));

As you can see, function names in PHP are quite self-descriptive. Sometimes this is a good thing, sometimes this makes function names unnecessarily complicated and type-error prone.

Searching

We can search strings to check whether they contain certain substrings (and their position or amount of occurrences). For example, if we wanted to check if users entered a valid email address, we could check whether the string contains the “@” character.

All of these functions will, if they can’t find what you’re looking for, or something else goes wrong, return the value false.

To search for the first occurrence of a substring, use one of these functions:

strstr($haystack, $needle [, $before_needle]); stristr($haystack, $needle [, $before_needle]);

This searches the string $haystack for the substring $needle, and returns everything that comes after it. The $before_needle parameter is optional. If you set it to true, the function will instead return everything that comes before the substring.

The difference between the first and second function is that little i in the middle. It means that the second function performs a case-insensitive search. Most functions have this variation, and I will point them out.

I’ll be using this way of describing syntax for the rest of the course, as the PHP manual (and most other programming manuals) do so as well.

$user_email = "[email protected]";

echo strstr($user_email, "@");       //Prints @gmail.com
echo strstr($user_email, "@", true); //Prints thatawesomeguy

$x = stristr($user_email, "girl");   //$x is false (thatawesomeguy is not thatawesomegirl)

To search for the position of a substring, use one of these functions:

strpos($haystack, $needle [, $offset]); strrpos($haystack, $needle [, $offset]); strripos($haystack, $needle [, $offset]);

This returns the index of the substring $needle in string $haystack. The optional $offset is an integer that determines from what index it starts looking; normally it starts at the first letter (index 0), but you can set it to start searching later.

The function strpos returns the first occurrence, strrpos the last occurrence (note the second ‘r’), and strripos does so case-insensitively.

$user_emails = "[email protected] | [email protected]";

echo strpos($user_emails, "@");  //Prints 15
echo strrpos($user_emails, "@"); //Prints 42

Substrings

If you don’t know the substring you’re looking for, but you do know at what index it should be, use

substr($haystack, $start [, $length]);

It returns the string starting from index $start until the end of the string. If you set $length, it will only return that amount of characters.

If you use a negative integer for $start, it will start that amount of characters from the end of the string (the same is the case for $length).

$video_url = "http://youtube.com/watch?v=BH-wP2TDUBQ";

//For example, if all the videos we reference on our website are 
//from youtube, all we need is to store the ID (BH-wP2TDUBQ).

//Two identical ways to do so are:
$video_id = substr($video_url, -11);
$video_id = substr($video_url, 27);

You can also just count how many times a substring occurs in a string. For this, use

substr_count($haystack, $needle, [$offset, $length]);

The $length parameter specifies how many characters to check after the $offset index. If omitted, the length is the same as the length of the whole string, which means it searches through the whole string and counts all the occurrences.

$achievements = "Got 1000 subscribers | Got 1000 views on a single day | Chose an awesome password | Invited 5 friends to the website";

//To know the total amount of achievements this user has, simply count the amount of seperators
echo substr_count($achievements, " | ") + 1;

Cutting

Now that we can find certain substrings within strings, it would be nice if we could cut them out of there, or at least divide the string into multiple substrings. For example, after having checked that the @ character is present in a string, we would like to select the domain name to see if it is valid. We don’t want [email protected] to resolve as a valid email address, but we do want [email protected] to be seen as valid.

Let’s start simple. To remove useless whitespace from a string use

Function

Description

trim($str)

Trim whitespace from both beginning and end

ltrim($str)

Trim whitespace only from the beginning (“from the left”)

rtrim($str)

Trim whitespace only from the end (“from the right”)

//Oh no, somebody accidentally added spaces in front of their 
//answer for our very, very important price quiz
$quiz_answer = "  RED  ";

//Fixed it.
echo trim($quiz_answer); //Prints RED

To cut a string into many substrings, you can split it into an array. For example, you could have a long string of data separated by a certain character, and then use that character to retrieve every individual piece again. For this, use

explode($delimiter, $haystack);

Note that it splits the whole string at every point it finds the delimiter, but it removes all occurrences of the delimiter itself.

//Oh no, the new blogger insisted on using his own syntax for storing blog post information
$post_information = "Hello dear readers, thanks for reading my blog!#22 January 2203#News#10 comments";

//Luckily, we can just split the string to get the information seperated;
print_r(explode("#", $post_information));
/*
	Array
	(
    	[0] => Hello dear readers, thanks for reading my blog!
    	[1] => 22 January 2203
    	[2] => News
    	[3] => 10 comments
	)
*/

Replacing

Last, but certainly not least, we might want to replace a piece of a string. (Instead of violently cutting it away.) (Or, you know, setting off explosions on the string.)

To replace all occurrences of a search string with a replacement string, use one of these

str_replace($search, $replace, $haystack [, $count]); str_ireplace($search, $replace, $haystack [, $count]);

The last parameter, if you set it, requires a variable to be put into it. After the function has executed, this variable will then hold the amount of replacements that have been made.

$post = "Great news! Peanut butter sales are increasing, so buy stock now!";

//Our boss read somewhere that the word Peanut makes potential customers feels uncomfortable
//Now we need to change every instance of the word with the friendlier sounding Apple
$post = str_replace("Peanut", "Apple", $post, $count_var);

echo $post;      //Prints: Great news! Apple butter sales are increasing, so buy stock now!
echo $count_var; //Prints: 1 	(because we've made one replacement)

Just as before, it’s possible that we don’t know the exact string, but we do know the index where it starts and ends. To perform a replacement in these cases, use

substr_replace($haystack, $replace, $start [, $length]);
//Let's say our comment system allows users to make their comments red
//To enable this fancy functionality, they need to start their comment with the word PANDA
$comment = "PANDAWow, this post was very informative!";

//Replace the first five characters with an opening HTML tag
$comment = substr_replace($comment, '<span style="color:red;">', 0, 5);

//Then add a closing tag at the end
$comment .= "</span>";

echo $comment;
//Prints a red comment reading "Wow, this post was very informative!"
CONTINUE WITH THIS COURSE
Do you like my tutorials?
To keep this site running, donate some motivational food!
Crisps
(€2.00)
Chocolate Milk
(€3.50)
Pizza
(€5.00)