match string php code example

Example 1: regex php

<?php
// First Verif your regex code with https://regex101.com/
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str); // Outputs 1

// test email with REGEX
if (!preg_match("/[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+.[a-zA-Z]{2,4}/", $emailAddress)){
    //Email address is invalid.
}

// use filter var to valide Email
if(filter_var($emailAddress, FILTER_VALIDATE_EMAIL)) 
{
     //The email address is valid.
} else{
     //The email address is invalid.
}


?>

Example 2: string match in php

//str_contains ( string $haystack , string $needle ) : bool

if (str_contains('Foo Bar Baz', 'Foo')) {
  echo 'Found';
}

Example 3: string match in php

You could use regular expressions as its better for word matching compared to
strpos, as mentioned by other users. A strpos check for are will also return 
true for strings such as: fare, care, stare, etc. These unintended matches can 
simply be avoided in regular expression by using word boundaries.

A simple match for are could look something like this:

$a = 'How are you?';

if (preg_match('/\bare\b/', $a)) {
    echo 'true';
}

Tags:

Php Example