Regex for PHP

Regex for PHP

You maybe looking for a way to perform string comparison. Regex, short for “regular expression,” is a powerful and flexible tool used for pattern matching and searching within text. In regex, we use the regex function to perform matching, validation , replacement and extraction.  Here are some of the examples how we use regex function in our web applications.
  1. Matching: You can use regex to find all instances of a particular pattern in a given text, such as finding all email addresses, phone numbers, or URLs in a document.
  2. Validation: Regex can help you validate input data, such as checking if a user-provided string is a valid email address, date, or phone number.
  3. Replacement: You can use regex to search and replace text based on a pattern. For example, you can replace all occurrences of one word with another.
  4. Extraction: Regex allows you to extract specific parts of text, such as capturing just the domain from a list of URLs.
Giving an example below
Imagine you wanted to to create a validation where a pattern only accept alphabet, numeric, slash and white space. This is how you would code it
PHP Script
********************
$str = "Coding Class Penang 123245";
$pattern = "/[a-zA-Z0-9 \/]+/";
echo preg_match($pattern, $str);

Result will be printed as 1 (True)

Related Posts
Leave a Reply

Your email address will not be published.Required fields are marked *