-
Notifications
You must be signed in to change notification settings - Fork 0
/
replace_pattern.php
70 lines (49 loc) · 1.93 KB
/
replace_pattern.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
<?php
/**
* PHP Replace Pattern within string
*
*
* @author Simeon Adedokun <femsimade@gmail.com>
* ====================================================
* Created on 4th January, 2021
*
*/
# Array of data to put in the string
$data = array(
"Username" => "theusername",
"Email" => "email@domain.com",
"FirstName" => "Simeon",
"LastName" => "Adedokun",
"VerificationLink" => "https://example.com/verify/49Adfa94sfkaff3akfjsfksafj",
);
//Specify possible patterns (or words) that can be replaced; any pattern not listed will not be replaced
$replaceablePatterns = array("Username","Email","FirstName","LastName","VerificationLink","MiddleName","Address");
// Here is the string template with string patterns in it
$template = "
Hello {FirstName} {LastName},<p>Your username is {Username}; your email address is {Email}. Click the link below to confirm your email address.<p>{VerificationLink}</p>
";
/* ******************************************************************************************** */
# Type 1
echo "<h2>Type 1</h2>";
foreach ($replaceablePatterns as $pattern) {
$search_pattern = "{".$pattern."}";//Concatenating the curly brackets to make the word appear differently
if(preg_match($search_pattern, $template))
//use preg_replace(pattern, replacement, subject)
$template = preg_replace($search_pattern, $data[$pattern], $template);
}
$template = str_replace("{", "", $template);
$template = str_replace("}", "", $template);
// You can now call the newly formed template
echo $template;
/* ******************************************************************************************** */
# Type 2
echo "<hr>";
echo "<h2>Type 2</h2>";
foreach ($replaceablePatterns as $pattern) {
$search_pattern = "{".$pattern."}";//Concatenating the curly brackets
if(strpos($template, $search_pattern))
$template = str_replace($search_pattern, $data[$pattern], $template);
}
// You can now call the newly formed template
echo $template
?>