1<?php
2// First Verif your regex code with https://regex101.com/
3$str = "Visit W3Schools";
4$pattern = "/w3schools/i";
5echo preg_match($pattern, $str); // Outputs 1
6
7// test email with REGEX
8if (!preg_match("/[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+.[a-zA-Z]{2,4}/", $emailAddress)){
9 //Email address is invalid.
10}
11
12// use filter var to valide Email
13if(filter_var($emailAddress, FILTER_VALIDATE_EMAIL))
14{
15 //The email address is valid.
16} else{
17 //The email address is invalid.
18}
19
20
21?>
22
1preg_match('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE);
1
2ive never used regex expressions till now and had loads of difficulty trying to convert a [url]link here[/url] into an href for use with posting messages on a forum, heres what i manage to come up with:
3
4$patterns = array(
5 "/\[link\](.*?)\[\/link\]/",
6 "/\[url\](.*?)\[\/url\]/",
7 "/\[img\](.*?)\[\/img\]/",
8 "/\[b\](.*?)\[\/b\]/",
9 "/\[u\](.*?)\[\/u\]/",
10 "/\[i\](.*?)\[\/i\]/"
11 );
12 $replacements = array(
13 "<a href=\"\\1\">\\1</a>",
14 "<a href=\"\\1\">\\1</a>",
15 "<img src=\"\\1\">",
16 "<b>\\1</b>",
17 "<u>\\1</u>",
18 "<i>\\1</i>"
19
20 );
21 $newText = preg_replace($patterns,$replacements, $text);
22
23at first it would collect ALL the tags into one link/bold/whatever, until i added the "?" i still dont fully understand it... but it works :)
24
1Modifier Description
2i Makes the match case insensitive
3m Specifies that if the string has newline or carriage
4 return characters, the ^ and $ operators will now
5 match against a newline boundary, instead of a
6 string boundary
7o Evaluates the expression only once
8s Allows use of . to match a newline character
9x Allows you to use white space in the expression for clarity
10g Globally finds all matches
11cg Allows a search to continue even after a global match fails
12