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.

  1. <?php
  2. /**
  3.     * strstr method
  4.     * @params (haystack, needle, [before_needle] )
  5.     * haystack = input string
  6.     * needle - substring
  7.     * before_needle (boolean) = if true, method returns the string before the substring
  8.     */
  9.  
  10. $check = strstr("A sample string", "sample", false);
  11. // return a string before the needle or from needle to last
  12.  
  13. /**
  14.     * strpos method
  15.     * @params (haystack, needle, [offset] )
  16.     * haystack = input string
  17.     * needle - substring
  18.     * before_needle (int|false) = search will start the given number of character
  19.     */
  20.  
  21.     $check = strpos("A sample string", "sample", false);
  22. // return the position of the first occurrence of the susbstring
  23.  
  24.  
  25.     /**
  26.     * str_contains method
  27.     * @params (haystack, needle, [offset] )
  28.     * haystack = input string
  29.     * needle - substring
  30.     */
  31.  
  32.     $check = strpos("A sample string", "sample", false);
  33. // returns true if substring is on the string, otherwise false
  34.  
  35.     /**
  36.     * preg_match method
  37.     * @params (pattern, subject, matches, [[flags], [offset]] )
  38.     * pattern = pattern to search
  39.     * subject = the input string
  40.     * matches = provides an array of matches
  41.     * flags = [PREG_OFFSET_CAPTURE, PREG_UNMATCHED_AS_NULL]
  42.     * offset = offset place of character
  43.     */
  44.  
  45.     $check = preg_match('/(sample)/', "A sample string", $matches);
  46.     // 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.

  1. [{
  2.     "phrase":"Cut to the chase",
  3.     "find" : "chase"
  4. },
  5. {
  6.     "phrase": "Rain on you parade",
  7.     "find": "Sun"
  8. },
  9. {
  10.     "phrase": "A cut below",
  11.     "find": "Cut"
  12. },
  13. {
  14.     "phrase": "Throw in the towel",
  15.     "find": "test"
  16. },
  17. {
  18.     "phrase": "Hard Pill to Swallow",
  19.     "find": "Hard"
  20. }]

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.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7.     <title>Check String if contains [string] in PHP</title>
  8.     <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" />
  9.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  10.  
  11.     <script src="https://code.jquery.com/jquery-3.6.2.min.js" integrity="sha256-2krYZKh//PcchRtd+H+VyyQoZ/e3EcrkxhM8ycwASPA=" crossorigin="anonymous"></script>
  12.     <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>
  13.     <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>
  14.  
  15.     <style>
  16.         html, body{
  17.             height: 100%;
  18.             width: 100%;
  19.         }
  20.         body{
  21.             display: flex;
  22.             height: 100%;
  23.             width: 100%;
  24.             flex-direction: column;
  25.         }
  26.         body>nav, body>footer{
  27.             flex-shrink: 1;
  28.         }
  29.         body>main{
  30.             flex-shrink: 1;
  31.             flex-grow: 1;
  32.             overflow: auto;
  33.             margin: 1em 0;
  34.         }
  35.         .badge.rouded-circle {
  36.             border-radius: 100%;
  37.             font-size: 13px;
  38.             padding: 0.5em;
  39.             height: 25px;
  40.             width: 25px;
  41.             text-align: center;
  42.         }
  43.     </style>
  44. </head>
  45. <body style="background:#EEF1FF">
  46.     <nav class="navbar navbar-expand-lg navbar-dark" style="background:#7FBCD2">
  47.         <div class="container">
  48.             <a class="navbar-brand" href="./">Check String if contains [string] in PHP</a>
  49.             <div>
  50.                 <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  51.             </div>
  52.         </div>
  53.     </nav>
  54.  
  55.     <main class="container-fluid">
  56.         <div class="col-lg-6 col-md-8 col-sm-12 col-xs-12 mx-auto">
  57.             <h2 class="text-center">Checking if the String contains a specific string using PHP</h2>
  58.             <hr>
  59.  
  60.             <div class="card mt-3 rounded-0">
  61.                 <div class="card-header">
  62.                     <div class="card-title"><b>Check List</b></div>
  63.                 </div>
  64.                 <div class="card-body rounded-0">
  65.                     <div class="container-fluid">
  66.                         <?php
  67.                         $use = isset($_GET['use']) ? $_GET['use'] : 'strstr';
  68.                         ?>
  69.                         <h3 class="text-center"><b>Using "<?= $use ?>"</b></h3>
  70.                         <div class="table-responsive">
  71.                             <table class="table table-bordered table-striped">
  72.                                 <thead>
  73.                                     <tr class="bg gradient bg-primary text-light">
  74.                                         <th class="p-1">Phrase</th>
  75.                                         <th class="p-1">Find</th>
  76.                                         <th class="p-1">Containing</th>
  77.                                         <th class="p-1">Return Value</th>
  78.                                     </tr>
  79.                                 </thead>
  80.                                 <tbody>
  81.                                 <?php
  82.                                 $data = file_get_contents("data.json");
  83.                                 $data = json_decode($data);
  84.                                 // print_r($data);exit;
  85.                                 foreach($data as $row):
  86.                                     switch($use){
  87.                                         case 'strstr':
  88.                                             $check = strstr(strtolower($row->phrase), strtolower($row->find));
  89.                                             $is_containing = ($check) ? true : false;
  90.                                             break;
  91.                                         case 'strpos':
  92.                                             $check = strpos(strtolower($row->phrase), strtolower($row->find));
  93.                                             $is_containing = ($check > -1) ? true : false;
  94.                                             break;
  95.                                         case 'str_contains':
  96.                                             $check = str_contains(strtolower($row->phrase), strtolower($row->find));
  97.                                             $is_containing = ($check) ? true : false;
  98.                                             break;
  99.                                         case 'preg_match':
  100.                                             $check = preg_match("/{$row->find}/i", $row->phrase, $matches);
  101.                                             $is_containing = ($check) ? true : false;
  102.                                             break;
  103.                                     }
  104.  
  105.                                 ?>
  106.                                 <tr>
  107.                                     <td class="p-1"><?= $row->phrase ?></td>
  108.                                     <td class="p-1"><?= $row->find ?></td>
  109.                                     <td class="p-1 text-center">
  110.                                         <?php if($is_containing): ?>
  111.                                             <span class="badge rouded-circle bg-success bg-gradient text-light"><i class="fa-solid fa-check"></i></span>
  112.                                         <?php else: ?>
  113.                                             <span class="badge rouded-circle bg-danger bg-gradient text-light"><i class="fa-solid fa-times"></i></span>
  114.                                         <?php endif; ?>
  115.                                     </td>
  116.                                     <td class="p-1"><?= is_bool($check) ? (($check) ? 'true' : 'false') : $check ?></td>
  117.                                 </tr>
  118.                                 <?php endforeach; ?>
  119.                                 </tbody>
  120.                             </table>
  121.                         </div>
  122.                     </div>
  123.                 </div>
  124.                 <div class="card-footer py-2">
  125.                     <div class="row justify-content-center">
  126.                         <div class="col-lg-3 col-md-6 col-sm-10 col-xs-12">
  127.                             <a class="btn btn-block w-100 btn-primary rounded-pill" href="./?use=strstr">strstr</a>
  128.                         </div>
  129.                         <div class="col-lg-3 col-md-6 col-sm-10 col-xs-12">
  130.                             <a class="btn btn-block w-100 btn-warning border rounded-pill" href="./?use=strpos">strpos</a>
  131.                         </div>
  132.                         <div class="col-lg-3 col-md-6 col-sm-10 col-xs-12">
  133.                             <a class="btn btn-block w-100 btn-info border rounded-pill" href="./?use=str_contains">str_contains</a>
  134.                         </div>
  135.                        
  136.                         <div class="col-lg-3 col-md-6 col-sm-10 col-xs-12">
  137.                             <a class="btn btn-block w-100 btn-success border rounded-pill" href="./?use=preg_match">preg_match</a>
  138.                         </div>
  139.                     </div>
  140.                 </div>
  141.             </div>
  142.         </div>
  143.     </main>
  144. <footer class="container-fluid py-3" style="background:#7FBCD2; color:#fff">
  145.     <div class="container-fluid my-2">
  146.         <div class="text-center">
  147.             <b>Check String if contains [string] in PHP &copy; 2022</b>
  148.         </div>
  149.     </div>
  150. </footer>
  151. </body>
  152. </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

Check if the String contains the specific String in PHP - DEMO App

Using "strstr" method

Check if the String contains the specific String in PHP - DEMO App

Using "strpos" method

Check if the String contains the specific String in PHP - DEMO App

Using "str_contains" method

Check if the String contains the specific String in PHP - DEMO App

Using "preg_match" method

Check if the String contains the specific String in PHP - DEMO App

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