-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuse-php-regex-validation.php
77 lines (60 loc) · 2.09 KB
/
use-php-regex-validation.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
// How to use RegEx Patterns for validation
// This function is test whether a regular expression matches a specific string.
// This function stops after the first match.
$match_pattern = preg_match($pattern, $string, $matches);
// This function is perform a global search of the input string.
// If preg_match_all() returns true, then you can iterate over the array specified by $matches.
$match_all_pattern = preg_match_all($pattern, $string, $matches);
// This function is perform a regular expression search and replace
$replace_pattern = preg_replace($pattern, $string_replacement, $string_input);
/**
*
* Test email address using preg_match() function
*
*/
$emailpattern = "/^\w+([\.-]?\w+)@\w+([-]?\w+)\.([a-z]{2,3})(\.[a-z]{2,3})?$/";
$emailval = 'yourname@example.com';
if (preg_match($emailpattern, $emailval)) {
echo "Found a match!";
} else {
echo "The regex pattern does not match.";
}
// Using function
function checkEmail( $str ) {
$emailpattern = "/^\w+([\.-]?\w+)@\w+([-]?\w+)\.([a-z]{2,3})(\.[a-z]{2,3})?$/";
return preg_match($emailpattern, $str);
}
echo checkEmail($emailval); // Return true of false
/**
*
* Get data using preg_match_all() function
*
*/
$string = "Name: <p>John Poul</p> Title: <b>PHP Guru</b>";
$pattern = "/<p>(.*)<\/p>/U";
preg_match_all ($pattern, $string, $matches);
echo $matches[0][0];
/**
*
* Replace all white space to WS using preg_replace() function
*
*/
function spaces($string) {
return ( preg_replace("/(\s+)/u",'WS',$string ) );
}
echo spaces("abc def ghi");
/**
*
* Find link from text and Replace actual link
*
*/
function addScheme($url, $scheme = 'http://') {
return parse_url($url, PHP_URL_SCHEME) === null ? $scheme . $url : $url;
}
function linkText( $text ) {
$urlRegex = "/(((https?:\/\/)|(www\.))[^\s]+)|([^\s]+\.([a-z]{2,})+)|([\.A-z0-9_\-\+]+[@][A-z0-9_\-]+([.][A-z0-9_\-\.]+)+[A-z]{2,4}$)|(\b\d+?\b(?!(?:[\.,]\d+)|(?:\s*(?:%|percent))))/";
return preg_replace_callback($urlRegex, function($url) {
return '<a href="'.addScheme( $url[0] ).'" target="_blank">'.$url[0].'</a>';
}, $text );
}