Checking String if contains specific String in PHP Tutorial
In this tutorial, you will learn how to Check if the String contains the specific String using PHP Language. The tutorial aims to provide IT/CS students and new programmers with a reference to learn the usage of the PHP built-in methods for searching in a string. Here, I will be providing some sample snippets that demonstrate the different effective ways of checking string if contains a string. A sample program source code zip file is also provided and is free to download.
How to Check if the String contains the specific String in PHP?
PHP comes with various built-in methods and some of them can be used for checking if a certain string, sentence, word, or phrase contains a specific string. The following list is the PHP methods that are useful and effective for achieving the main goal of this tutorial
- strstr - a PHP method that searches or finds the first occurrence of a string. Note that this method is case-sensitive. you can use stristr method which works the same but is case-insensitive.
- strpos - a PHP method that searches or finds the position of the first occurrence in a string. It is also a case-sensitive method. You can use stripos method for case-insensitive
- str_contains - a PHP method that determines whether the given string contains the given substring. It also performs case-sensitive checking.
- preg_match - is a method in PHP which performs string matching using regular expression.
Syntax
Here's a simple snippet that demonstrates the usage of the PHP method listed above.
- <?php
- /**
- * strstr method
- * @params (haystack, needle, [before_needle] )
- * haystack = input string
- * needle - substring
- * before_needle (boolean) = if true, method returns the string before the substring
- */
- // return a string before the needle or from needle to last
- /**
- * strpos method
- * @params (haystack, needle, [offset] )
- * haystack = input string
- * needle - substring
- * before_needle (int|false) = search will start the given number of character
- */
- // return the position of the first occurrence of the susbstring
- /**
- * str_contains method
- * @params (haystack, needle, [offset] )
- * haystack = input string
- * needle - substring
- */
- // returns true if substring is on the string, otherwise false
- /**
- * preg_match method
- * @params (pattern, subject, matches, [[flags], [offset]] )
- * pattern = pattern to search
- * subject = the input string
- * matches = provides an array of matches
- * flags = [PREG_OFFSET_CAPTURE, PREG_UNMATCHED_AS_NULL]
- * offset = offset place of character
- */
- // returns 1 if has a match, 0 if does not have, and false for failures
Example
Here are the snippets that result in a simple web application written in HTML and PHP that demonstrate how to use the given PHP methods for checking if a certain string contains a specific string/substring.
JSON Data
The following is a JSON that contains some sample phrases to be used for this demo application. It also contains the string to search in the given string/phrase. Save this file as data.json.
- [{
- "phrase":"Cut to the chase",
- "find" : "chase"
- },
- {
- "phrase": "Rain on you parade",
- "find": "Sun"
- },
- {
- "phrase": "A cut below",
- "find": "Cut"
- },
- {
- "phrase": "Throw in the towel",
- "find": "test"
- },
- {
- "phrase": "Hard Pill to Swallow",
- "find": "Hard"
- }]
Interface
The snippet below is a combined HTML and PHP script that displays the list of phrases. It contains also the PHP scripts that check the string/phrase if containing the specified string using the mentioned PHP methods. Save the file as index.php.
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Check String if contains [string] in PHP</title>
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
- <script src="https://code.jquery.com/jquery-3.6.2.min.js" integrity="sha256-2krYZKh//PcchRtd+H+VyyQoZ/e3EcrkxhM8ycwASPA=" crossorigin="anonymous"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
- <style>
- html, body{
- height: 100%;
- width: 100%;
- }
- body{
- display: flex;
- height: 100%;
- width: 100%;
- flex-direction: column;
- }
- body>nav, body>footer{
- flex-shrink: 1;
- }
- body>main{
- flex-shrink: 1;
- flex-grow: 1;
- overflow: auto;
- margin: 1em 0;
- }
- .badge.rouded-circle {
- border-radius: 100%;
- font-size: 13px;
- padding: 0.5em;
- height: 25px;
- width: 25px;
- text-align: center;
- }
- </style>
- </head>
- <body style="background:#EEF1FF">
- <nav class="navbar navbar-expand-lg navbar-dark" style="background:#7FBCD2">
- <div class="container">
- <a class="navbar-brand" href="./">Check String if contains [string] in PHP</a>
- <div>
- <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
- </div>
- </div>
- </nav>
- <main class="container-fluid">
- <div class="col-lg-6 col-md-8 col-sm-12 col-xs-12 mx-auto">
- <h2 class="text-center">Checking if the String contains a specific string using PHP</h2>
- <hr>
- <div class="card mt-3 rounded-0">
- <div class="card-header">
- <div class="card-title"><b>Check List</b></div>
- </div>
- <div class="card-body rounded-0">
- <div class="container-fluid">
- <?php
- ?>
- <h3 class="text-center"><b>Using "<?= $use ?>"</b></h3>
- <div class="table-responsive">
- <table class="table table-bordered table-striped">
- <thead>
- <tr class="bg gradient bg-primary text-light">
- <th class="p-1">Phrase</th>
- <th class="p-1">Find</th>
- <th class="p-1">Containing</th>
- <th class="p-1">Return Value</th>
- </tr>
- </thead>
- <tbody>
- <?php
- // print_r($data);exit;
- foreach($data as $row):
- switch($use){
- case 'strstr':
- $is_containing = ($check) ? true : false;
- break;
- case 'strpos':
- $is_containing = ($check > -1) ? true : false;
- break;
- case 'str_contains':
- $is_containing = ($check) ? true : false;
- break;
- case 'preg_match':
- $is_containing = ($check) ? true : false;
- break;
- }
- ?>
- <tr>
- <td class="p-1"><?= $row->phrase ?></td>
- <td class="p-1"><?= $row->find ?></td>
- <td class="p-1 text-center">
- <?php if($is_containing): ?>
- <span class="badge rouded-circle bg-success bg-gradient text-light"><i class="fa-solid fa-check"></i></span>
- <?php else: ?>
- <span class="badge rouded-circle bg-danger bg-gradient text-light"><i class="fa-solid fa-times"></i></span>
- <?php endif; ?>
- </td>
- </tr>
- <?php endforeach; ?>
- </tbody>
- </table>
- </div>
- </div>
- </div>
- <div class="card-footer py-2">
- <div class="row justify-content-center">
- <div class="col-lg-3 col-md-6 col-sm-10 col-xs-12">
- <a class="btn btn-block w-100 btn-primary rounded-pill" href="./?use=strstr">strstr</a>
- </div>
- <div class="col-lg-3 col-md-6 col-sm-10 col-xs-12">
- <a class="btn btn-block w-100 btn-warning border rounded-pill" href="./?use=strpos">strpos</a>
- </div>
- <div class="col-lg-3 col-md-6 col-sm-10 col-xs-12">
- <a class="btn btn-block w-100 btn-info border rounded-pill" href="./?use=str_contains">str_contains</a>
- </div>
- <div class="col-lg-3 col-md-6 col-sm-10 col-xs-12">
- <a class="btn btn-block w-100 btn-success border rounded-pill" href="./?use=preg_match">preg_match</a>
- </div>
- </div>
- </div>
- </div>
- </div>
- </main>
- <footer class="container-fluid py-3" style="background:#7FBCD2; color:#fff">
- <div class="container-fluid my-2">
- <div class="text-center">
- <b>Check String if contains [string] in PHP © 2022</b>
- </div>
- </div>
- </footer>
- </body>
- </html>
That's It! The program will check the phrases upon running the application. Click the method buttons located below the table to select the PHP method to be used for checking.
Snapshot
Here are the result snapshots of the demo application
Interface
Using "strstr" method
Using "strpos" method
Using "str_contains" method
Using "preg_match" method
I also provided the complete source code zip file of the Demo Application I have given above. The zip file is free to download on this website. The download button is located below this article.
DEMO VIDEO
That's the end of this tutorial. I hope this Checking String if contains a specific String in PHP Tutorial helps you with what you are looking for and you'll find this useful for your current and future PHP Projects.
Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding :)
Add new comment
- 438 views