• We just launched and are currently in beta. Join us as we build and grow the community.

Checking String if contains specific String in PHP Tutorial

Curls

Backend System Visionary
C Rep
0
0
0
Rep
0
C Vouches
0
0
0
Vouches
0
Posts
45
Likes
19
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
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. $check

    =

    strstr

    (

    "A sample string"

    ,

    "sample"

    ,

    false

    )

    ;
  10. // return a string before the needle or from needle to last

  11. /**
  12. * strpos method
  13. * @params (haystack, needle, [offset] )
  14. * haystack = input string
  15. * needle - substring
  16. * before_needle (int|false) = search will start the given number of character
  17. */

  18. $check

    =

    strpos

    (

    "A sample string"

    ,

    "sample"

    ,

    false

    )

    ;
  19. // return the position of the first occurrence of the susbstring


  20. /**
  21. * str_contains method
  22. * @params (haystack, needle, [offset] )
  23. * haystack = input string
  24. * needle - substring
  25. */

  26. $check

    =

    strpos

    (

    "A sample string"

    ,

    "sample"

    ,

    false

    )

    ;
  27. // returns true if substring is on the string, otherwise false

  28. /**
  29. * preg_match method
  30. * @params (pattern, subject, matches, [[flags], [offset]] )
  31. * pattern = pattern to search
  32. * subject = the input string
  33. * matches = provides an array of matches
  34. * flags = [PREG_OFFSET_CAPTURE, PREG_UNMATCHED_AS_NULL]
  35. * offset = offset place of character
  36. */

  37. $check

    =

    preg_match

    (

    '/(sample)/'

    ,

    "A sample string"

    ,

    $matches

    )

    ;
  38. // 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. <script src="https://code.jquery.com/jquery-3.6.2.min.js" integrity="sha256-2krYZKh//PcchRtd+H+VyyQoZ/e3EcrkxhM8ycwASPA=" crossorigin="anonymous"></script>
  11. <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>
  12. <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>

  13. <style>
  14. html, body{
  15. height: 100%;
  16. width: 100%;
  17. }
  18. body{
  19. display: flex;
  20. height: 100%;
  21. width: 100%;
  22. flex-direction: column;
  23. }
  24. body>nav, body>footer{
  25. flex-shrink: 1;
  26. }
  27. body>main{
  28. flex-shrink: 1;
  29. flex-grow: 1;
  30. overflow: auto;
  31. margin: 1em 0;
  32. }
  33. .badge.rouded-circle {
  34. border-radius: 100%;
  35. font-size: 13px;
  36. padding: 0.5em;
  37. height: 25px;
  38. width: 25px;
  39. text-align: center;
  40. }
  41. </style>
  42. </head>
  43. <body style="background:#EEF1FF">
  44. <nav class="navbar navbar-expand-lg navbar-dark" style="background:#7FBCD2">
  45. <div class="container">
  46. <a class="navbar-brand" href="./">Check String if contains [string] in PHP</a>
  47. <div>
  48. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  49. </div>
  50. </div>
  51. </nav>

  52. <main class="container-fluid">
  53. <div class="col-lg-6 col-md-8 col-sm-12 col-xs-12 mx-auto">
  54. <h2 class="text-center">Checking if the String contains a specific string using PHP</h2>
  55. <hr>

  56. <div class="card mt-3 rounded-0">
  57. <div class="card-header">
  58. <div class="card-title"><b>Check List</b></div>
  59. </div>
  60. <div class="card-body rounded-0">
  61. <div class="container-fluid">
  62. <?php
  63. $use

    =

    isset

    (

    $_GET

    [

    'use'

    ]

    )

    ? $_GET

    [

    'use'

    ]

    :

    'strstr'

    ;
  64. ?>
  65. <h3 class="text-center"><b>Using "<?=

    $use

    ?>

    "</b></h3>
  66. <div class="table-responsive">
  67. <table class="table table-bordered table-striped">
  68. <thead>
  69. <tr class="bg gradient bg-primary text-light">
  70. <th class="p-1">Phrase</th>
  71. <th class="p-1">Find</th>
  72. <th class="p-1">Containing</th>
  73. <th class="p-1">Return Value</th>
  74. </tr>
  75. </thead>
  76. <tbody>
  77. <?php
  78. $data

    =

    file_get_contents

    (

    "data.json"

    )

    ;
  79. $data

    =

    json_decode

    (

    $data

    )

    ;
  80. // print_r($data);exit;
  81. foreach

    (

    $data

    as

    $row

    )

    :
  82. switch

    (

    $use

    )

    {
  83. case

    'strstr'

    :
  84. $check

    =

    strstr

    (

    strtolower

    (

    $row

    ->

    phrase

    )

    ,

    strtolower

    (

    $row

    ->

    find

    )

    )

    ;
  85. $is_containing

    =

    (

    $check

    )

    ? true

    :

    false

    ;
  86. break

    ;
  87. case

    'strpos'

    :
  88. $check

    =

    strpos

    (

    strtolower

    (

    $row

    ->

    phrase

    )

    ,

    strtolower

    (

    $row

    ->

    find

    )

    )

    ;
  89. $is_containing

    =

    (

    $check

    >

    -

    1

    )

    ? true

    :

    false

    ;
  90. break

    ;
  91. case

    'str_contains'

    :
  92. $check

    =

    str_contains(

    strtolower

    (

    $row

    ->

    phrase

    )

    ,

    strtolower

    (

    $row

    ->

    find

    )

    )

    ;
  93. $is_containing

    =

    (

    $check

    )

    ? true

    :

    false

    ;
  94. break

    ;
  95. case

    'preg_match'

    :
  96. $check

    =

    preg_match

    (

    "/{$row->find}

    /i"

    ,

    $row

    ->

    phrase

    ,

    $matches

    )

    ;
  97. $is_containing

    =

    (

    $check

    )

    ? true

    :

    false

    ;
  98. break

    ;
  99. }

  100. ?>
  101. <tr>
  102. <td class="p-1"><?=

    $row

    ->

    phrase

    ?>

    </td>
  103. <td class="p-1"><?=

    $row

    ->

    find

    ?>

    </td>
  104. <td class="p-1 text-center">
  105. <?php

    if

    (

    $is_containing

    )

    :

    ?>
  106. <span class="badge rouded-circle bg-success bg-gradient text-light"><i class="fa-solid fa-check"></i></span>
  107. <?php

    else

    :

    ?>
  108. <span class="badge rouded-circle bg-danger bg-gradient text-light"><i class="fa-solid fa-times"></i></span>
  109. <?php

    endif

    ;

    ?>
  110. </td>
  111. <td class="p-1"><?=

    is_bool

    (

    $check

    )

    ? (

    (

    $check

    )

    ? 'true'

    :

    'false'

    )

    :

    $check

    ?>

    </td>
  112. </tr>
  113. <?php

    endforeach

    ;

    ?>
  114. </tbody>
  115. </table>
  116. </div>
  117. </div>
  118. </div>
  119. <div class="card-footer py-2">
  120. <div class="row justify-content-center">
  121. <div class="col-lg-3 col-md-6 col-sm-10 col-xs-12">
  122. <a class="btn btn-block w-100 btn-primary rounded-pill" href="./?use=strstr">strstr</a>
  123. </div>
  124. <div class="col-lg-3 col-md-6 col-sm-10 col-xs-12">
  125. <a class="btn btn-block w-100 btn-warning border rounded-pill" href="./?use=strpos">strpos</a>
  126. </div>
  127. <div class="col-lg-3 col-md-6 col-sm-10 col-xs-12">
  128. <a class="btn btn-block w-100 btn-info border rounded-pill" href="./?use=str_contains">str_contains</a>
  129. </div>

  130. <div class="col-lg-3 col-md-6 col-sm-10 col-xs-12">
  131. <a class="btn btn-block w-100 btn-success border rounded-pill" href="./?use=preg_match">preg_match</a>
  132. </div>
  133. </div>
  134. </div>
  135. </div>
  136. </div>
  137. </main>
  138. <footer class="container-fluid py-3" style="background:#7FBCD2; color:#fff">
  139. <div class="container-fluid my-2">
  140. <div class="text-center">
  141. <b>Check String if contains [string] in PHP &copy; 2022</b>
  142. </div>
  143. </div>
  144. </footer>
  145. </body>
  146. </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 :)


Download
You must upgrade your account or reply in the thread to view hidden text.
 

452,292

323,348

323,357

Top