PHP Finding Text in a String With Preg_Match() or strpos()


PHP Finding Text in a String

With PHP, you may want to see if text exists in a string. For example, you may have database output from an api and you want to search the rows for particular string. Or, you may want to make conditional statements based on the database output. For example, you may to sort the same 'John' from all other names in a loop. The code below shows two methods for doing so using the preg_match() function and the strpos() function.

<?php
        $complete_text = "Giants Home Game";
        $string = "Giants";
        $pos = strpos($complete_text, $string);
        if($pos === false ) {
        echo "It is not in the string.";
        }else{ echo "Yes it is in the string."; } ?>
        
        <?php

        $string_entire = "SF Giants in World Series";
        $string_to_find = 'SF Giants';            
        if(preg_match("/$string_to_find/", $string_entire)==true) {
        echo "<br/>Found it!";
        }
        else {
        echo "<br/>Not in the string"; }
        ?>