How to Check if String Contains Regex in PHP?

03-Apr-2023

.

Admin

How to Check if String Contains Regex in PHP?

Hi Dev,

Today, how to check if string contains regex in php? is our main topic. I’m going to show you about php regular expressions. In this article, we will implement a php program to check if a string has a regex. you'll learn how do i allow regex in php?. you will do the following things for check if a string consists only of regex.

There are example to provides a variety of functions that allow you to use regular expressions. The preg_match(), preg_match_all() and preg_replace() functions are some of the most commonly used ones

Example 1


index.php

<?php

//Use a regular expression to do a case-insensitive

$str = "Visit W3Schools";

$pattern = "/w3schools/i";

echo preg_match($pattern, $str);

?>

Output:

1

Example 2

index.php

<?php

//Use a regular expression to do a case-insensitive

$str = "The rain in SPAIN falls mainly on the plains.";

$pattern = "/ain/i";

echo preg_match_all($pattern, $str);

?>

Output:

4

Example 3

index.php

<?php

//Use a case-insensitive regular expression

$str = "Visit Microsoft!";

$pattern = "/microsoft/i";

echo preg_replace($pattern, "Nicesnippets.com", $str);

?>

Output:

Visit Nicesnippets.com

Example 4

index.php

<?php

//Use grouping to search for the word

$str = "Apples and bananas.";

$pattern = "/ba(na){2}/i";

echo preg_match($pattern, $str);

?>

Output:

1

I hope it could help you...

#PHP