How to Find a String in String PHP

104 18
    • 1). Decide how you will run your PHP code. There are a couple of different ways available to you. If you have a PHP server, you can execute code using PHP files. If you do not have access to a PHP server, you can use an online PHP interpreter. Enter the code in this tutorial into either a PHP file or the online PHP interpreter.

    • 2). Begin your PHP program with the following statement:

      <?php

    • 3). Declare a string through which you will search. This string can contain any text you like. For example, you could write this:

      $stringToSearch = 'This is the string you will search in.';

    • 4). Declare a string that will hold the word you are going to look for in the other string. Search phrases are sometimes called patterns, so you could name your search phrase variable 'searchPattern.' To search for the word 'the,' you could write the following statement:

      $searchPattern = 'the';

    • 5). Use the strpos() function to look for the string 'the' in the larger string 'This is the string you will search in.' To do this, pass the variable names for these two strings to strpos(). The function will look for the string, and if it finds it, it will return the numerical position of the substring in the larger string. You can store this position in another variable like this:

      $locationOfString = strpos($stringToSearch , $searchPattern );

    • 6). Test to see if the string was found. You can do this by testing the variable $locationOfSring in an "if" statement. If the string is not found, this variable will evaluate as false. You can print a message informing the user that the string was not found, like this:

      if($locationOfString == false) { print('string not found'); }

    • 7). Print the location of the string if it was found, like this:

      else { printf('string found at position %d', $locationOfString); }

    • 8). Conclude your PHP program with the statement below:

      ?>

      Your program is now ready to be tested on your PHP server or online PHP interpreter.

Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.