PHP strstr function – Searching for a needle in a haystack

phpstrstrPHP is a very powerful addition to any HTML code because PHP offers a number of built-in functions which allow you to work with and manipulate data. The built-in functions make it easy to control strings, replace strings, find strings, find parts of strings and much more.

These functions are extremely important for PHP programming and the functions are fairly simple to implement once you’re familiar with PHP syntax, coding methods and notation.

To understand this tutorial, you need to understand some basic PHP programming principles. You need to know what a variable is and how to declare one. You also need to know what a function and how to implement functions in your code. You need some fundamental understanding of other PHP topics like what a string is and also how to use basic programming functions to output the results of various functions. To learn the basics of php, udemy offers a PHP course for absolute beginners which will teach you the basics of PHP and more.

What the strstr function is

The strstr function is a built-in function that PHP programmers can use in their code to search various strings and variables to find values that they need to access and manipulate.

This function essentially allows you to search a target string, called the haystack, to find portions of that string, called the needle. The function is based on the specific parameters which you need to specify within the function itself.

Here is the syntax for the strstr function. We will go through each part of the strstr statement in detail below.

string strstr ( string $haystack ,mixed $needle [, bool $before_needle = false ] )

The function is called using the strstr function call and the parameters allow you to specify what string or variable to search as well as the parameters of the specific search. Now let’s break that down into something that makes sense so that you can implement the statement in your PHP code.

If you don’t know what parameters are or syntax is then you can take a course in the fundamentals of PHP programming which will explain what these concepts are and also how to apply them.

What strstr stands for in the syntax

Strstr is the function name. You use a function name to call a function, This essentially means you get the program to execute the function by typing strstr. When you type strstr, the program executes a set of predefined, built-in procedures which allows the server to perform a very specific search action. In this case, the server uses its built-in function called strstr to search for something that you define within the brackets based on the criteria you want to search for. What information it will search through and the information it’s going to be searching for are called parameters and are defined in the brackets after the functions is called.

What the string $haystack means in the syntax

The first parameter which is specified in the brackets after calling the strstr procedure, is called the haystack parameter. This parameter tells the function what information to search through. This search is not confined to searching strings only. You can use the parameter to search a string or a variable that you have previously defined. This is part of what makes this function very useful and powerful.

Here is some basic code that you would use to tell the function to search the string “Hello World.”:

The above code won’t produce any results as such, because you have not told the function what to search for or what to do with the results yet, but it tells the function that it must search the string: “Hello World.”

What the string $needle means in the syntax

The second parameter specified within the brackets is called the needle parameter. This parameter tells the function what you are looking for in the haystack in other words what you are looking for in the information you are searching. When the function finds the needle it makes a note of what characters occur from the needle onwards. It is important to note that the needle is included in the output of the function. Once the needle is found, the function then returns all of the rest characters to the main function or program as the answer to what you were searching for. So let’s add a needle to code we were working on:

The code above tells the function to search the string “Hello World.” and if it finds “e” then it needs to record and return all the characters from the e to the end of the string you so you can do something with them. If we assign the output of the strstr function to a variable then we can display the output on the screen. The code would then look like this:

Now the function would search “Hello World.” to see if the string contains an e. If it finds an “e” then it will record all the characters that occur after the e and save that information into a variable called $stringFound. Using the echo command to output the string, it will then display $stringFound on the screen. So the output of the above code example will be:

ello World.

It is also important to note that it will return all of the information it finds to the end of the string so this function is very useful when you are unsure of how long a string or variable may be. It is also very useful for data which varies in length and structure – where the identifier you are looking for may be in a different location within the data.

For example, when you search an email address the length of the user name and the length of the domain name may vary so you can’t set a specific location to search for the @ if you were wanting to return either the user name or domain.

The strstr function is case sensitive.

One more thing to note at this point, is that the strstr function is case sensitive which means that if we had used “E” as the needle instead of “e” then the function would have returned a “string not found” as the output.

For example:

Would have output of:

String not found

So it’s important use case sensitive data in the needle parameter. If you want to use a case insensitive search function then the stristr function is available for that type of search.

The power of using variables in the strstr function

As mentioned above, the parameters of the strstr function can include strings as well as variables. By including a variable it means you can literally search almost anything. You can search file names, file extensions, folders, and images. The sky is almost the limit here. Here are some examples of how you use the first parameter.

Code example – using a string as the $haystack parameter:

Code example – using a variable as the $haystack parameter:

Both code examples above will use the strstr function to search the phrase hello world. But they are different because in the first example you would have to know what the search term was for each search. The second version gives you the power of searching a variable. By using a variable, you can now write code to place almost anything into that variable.

Let say for example you have a list of images on your website, some of which contain a specific object. Assuming you need to know how many pictures contain images of that object – like banana’s for example – then strstr gives you a way finding those pictures even if their names vary in length and they have different file extensions. By writing code to load all of the file names into a variable, you could then use the strstr function to search that variable to find all of the images which include banana in the file name and then use that data as you need to..

Practical example of using the strstr function

Let’s say for example that a user enters their name on your website when they log in. You can use that information to output a personal greeting to each user. Here is an example of how you could do that:

The output of the above code will be:

Welcome Mr. Blogs.

The needle parameter can search for an ascii value

The needle parameter can also search the $haystack string for an ascii value instead of searching for a specified character. It will then return the characters that follow that ascii value along with the ascii value itself.

Using our example, let’s assume a user enters his name and surname when he logs in. You could use B of his surname as the second parameter or you can use the ascii value of the character you are searching for like this:

Will now result in the following output:

Welcome Mr. Blogs

Now let’s look at the code above again but assume the user’s name was Joe Barry Blogs. If you used the code we did before then:

Would result in the following output:

Welcome Mr. Barry Blogs.

But you don’t necessarily want to search for the first B in this case, but actually for the second instance of B. This is where the third parameter of the function comes becomes very important and powerful in this function.

Using the third optional parameter in the strstr function.

If you go back to the syntax definition of the strstr function you will notice that there are 3 parameters which you can use to define how the function operates:

string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

So now that we know how the $haystack parameter and the $needle parameter work, we need to talk about the third parameter of the function. The [, bool $before_needle = false ] parameter. This is an optional parameter and the function will work even if you do not add anything to this section of the syntax, but this optional parameter gives the function a lot more functionality as you will see in our example of Joe Barry Blogs.

The third parameter can be expressed as a number or as a Boolean. This parameter is used to indicate where the function must start searching the $haystack string from. So let’s tell the program we don’t want to search from the first character in the string but that we’d rather begin the search from some later point in the string. In this case we want to only start searching from after the “Barry” part of the string. This is the 5th character of the string. So if we write the parameter as strstr($userName, B, 6) for example, then the program will skip to the 6th character within the string before it starts to search for the needle.

Here is what the code will look like:

Will now result in the following output:

Welcome Mr. Blogs

Setting the third parameter to “true”

So far we have only used the strstr function to return the characters which appear after the needle. The third parameter however also allows us to search for characters come before the needle by setting the optional parameter to true.

This second built-in function very useful too. If the parameter is set to ‘true’ then the program will return all of the characters it finds before the needle. So let’s take a look at the code again using the ‘true’ parameter:

Will now result in the following output:

Welcome Joe

So the parameters of the strstr function returns all characters found after the needle, or it returns all characters found before the needle if the third parameter is set to true. Note that when it returns the characters after the needle, then the needle is included in the results but when it returns the characters before the needle, the needle is not included.

Now let’s see how we can really use this function to make our lives easier.

A Practical Code Example of Using strstr

Suppose you have a database on your website that contains a list of book names and authors. The information kept in database lists the books and authors in the following format:

“David Copperfield – Charles Dickens”

“A Tale of Two Cities – Charles Dickens”

“The Da Vinci Code – Dan Brown”

“Think and Grow Rich – Napoleon Hill”

You can now use the strstr code to allow the user to search your database for who wrote a particular book.

To do this you would need to first open the database to extract the book names into a variable in your code. This would require some other functions and coding. For a more advanced course on using PHP and a database like mySql try the Pearson PHP and mySql course.

The program structure and code for the above would look something like this:

Now that you know how powerful the strstr in PHP can be, I hope you will consider implementing PHP in your web pages. There excellent PHP courses on udemy and even courses which can help you become a certified web developer.