-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy path01-string-helpers.php
More file actions
347 lines (303 loc) · 9.95 KB
/
01-string-helpers.php
File metadata and controls
347 lines (303 loc) · 9.95 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
<?php
/**
* Example: String Helper Functions
*
* Demonstrates string manipulation helpers
*/
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../helpers.php';
use tommyknocker\pdodb\helpers\Db;
$db = createExampleDb();
$driver = getCurrentDriver($db);
echo "=== String Helper Functions Example (on $driver) ===\n\n";
// Setup
$schema = $db->schema();
recreateTable($db, 'users', [
'id' => $schema->primaryKey(),
'first_name' => $schema->text(),
'last_name' => $schema->text(),
'email' => $schema->text(),
'bio' => $schema->text(),
]);
$db->find()->table('users')->insertMulti([
['first_name' => 'john', 'last_name' => 'doe', 'email' => 'JOHN@EXAMPLE.COM', 'bio' => ' Software Developer '],
['first_name' => 'jane', 'last_name' => 'smith', 'email' => 'JANE@EXAMPLE.COM', 'bio' => 'Product Manager'],
['first_name' => 'bob', 'last_name' => 'johnson', 'email' => 'BOB@TEST.COM', 'bio' => ' Designer '],
]);
echo "✓ Test data inserted\n\n";
// Example 1: CONCAT - Combine strings
echo "1. CONCAT - Full names...\n";
$users = $db->find()
->from('users')
->select([
'id',
'full_name' => Db::concat(Db::upper('first_name'), ' ', Db::upper('last_name'))
])
->get();
foreach ($users as $user) {
echo " • {$user['full_name']}\n";
}
echo "\n";
// Example 10: LEFT and RIGHT
echo "10. LEFT and RIGHT - Extract edges of strings...\n";
$sides = $db->find()
->from('users')
->select([
'first_name',
'left2' => Db::left('first_name', 2),
'right2' => Db::right('first_name', 2)
])
->limit(3)
->get();
foreach ($sides as $row) {
echo " • {$row['first_name']} → LEFT(2)={$row['left2']}, RIGHT(2)={$row['right2']}\n";
}
echo "\n";
// Example 11: POSITION - Find substring index (1-based)
echo "11. POSITION - Find '@' in email...\n";
$positions = $db->find()
->from('users')
->select([
'email',
'at_pos' => Db::position('@', 'email')
])
->limit(3)
->get();
foreach ($positions as $row) {
echo " • {$row['email']} → '@' at position {$row['at_pos']}\n";
}
echo "\n";
// Example 12: REPEAT and REVERSE (now emulated for SQLite)
echo "12. REPEAT and REVERSE - Banner formatting...\n";
$banners = $db->find()
->from('users')
->select([
'first_name',
'banner' => Db::repeat('-', 3),
'reversed' => Db::reverse('first_name')
])
->limit(2)
->get();
foreach ($banners as $row) {
echo " • {$row['first_name']} → banner={$row['banner']}, reversed={$row['reversed']}\n";
}
echo "\n";
// Example 13: LPAD and RPAD (now emulated for SQLite)
echo "13. LPAD and RPAD - Align strings...\n";
$padded = $db->find()
->from('users')
->select([
'first_name',
'left_padded' => Db::padLeft('first_name', 8, ' '),
'right_padded' => Db::padRight('first_name', 8, '.')
])
->limit(3)
->get();
foreach ($padded as $row) {
echo " • '{$row['left_padded']}' | '{$row['right_padded']}'\n";
}
echo "\n";
// Example 2: UPPER and LOWER
echo "2. UPPER and LOWER - Case conversion...\n";
$users = $db->find()
->from('users')
->select([
'first_name',
'upper_name' => Db::upper('first_name'),
'lower_email' => Db::lower('email')
])
->limit(1)
->getOne();
echo " Original: {$users['first_name']}\n";
echo " UPPER: {$users['upper_name']}\n";
echo " Email (lower): {$users['lower_email']}\n\n";
// Example 3: TRIM - Remove whitespace
echo "3. TRIM - Remove whitespace...\n";
$users = $db->find()
->from('users')
->select([
'bio',
'trimmed' => Db::trim('bio'),
'length_before' => Db::length('bio'),
'length_after' => Db::length(Db::trim('bio'))
])
->where(Db::like('bio', '% %'))
->get();
foreach ($users as $user) {
echo " Before: \"{$user['bio']}\" (length: {$user['length_before']})\n";
echo " After: \"{$user['trimmed']}\" (length: {$user['length_after']})\n";
}
echo "\n";
// Example 4: LENGTH - String length
echo "4. LENGTH - Find users with long bios...\n";
$users = $db->find()
->from('users')
->select(['first_name', 'bio_length' => Db::length('bio')])
->where(Db::length('bio'), 15, '>')
->get();
echo " Users with long bios:\n";
foreach ($users as $user) {
echo " • {$user['first_name']} (bio length: {$user['bio_length']})\n";
}
echo "\n";
// Example 5: SUBSTRING - Extract part of string
echo "5. SUBSTRING - Extract first 3 characters...\n";
$users = $db->find()
->from('users')
->select([
'first_name',
'short_name' => Db::substring('first_name', 1, 3)
])
->get();
foreach ($users as $user) {
echo " • {$user['first_name']} → {$user['short_name']}\n";
}
echo "\n";
// Example 6: REPLACE - String replacement
echo "6. REPLACE - Mask email addresses...\n";
$users = $db->find()
->from('users')
->select([
'first_name',
'masked_email' => Db::replace(Db::lower('email'), '@', '(at)')
])
->get();
foreach ($users as $user) {
echo " • {$user['first_name']}: {$user['masked_email']}\n";
}
echo "\n";
// Example 7: LTRIM and RTRIM operations
echo "7. LTRIM and RTRIM operations...\n";
$users = $db->find()
->from('users')
->select([
'bio',
'left_trimmed' => Db::ltrim('bio'),
'right_trimmed' => Db::rtrim('bio'),
'both_trimmed' => Db::trim('bio')
])
->where(Db::like('bio', '% %'))
->get();
foreach ($users as $user) {
echo " Original: \"{$user['bio']}\"\n";
echo " LTRIM: \"{$user['left_trimmed']}\"\n";
echo " RTRIM: \"{$user['right_trimmed']}\"\n";
echo " TRIM: \"{$user['both_trimmed']}\"\n";
}
echo "\n";
// Example 8: Combine multiple string functions
echo "8. Combining string functions...\n";
$users = $db->find()
->from('users')
->select([
'first_name',
'last_name',
// Use helpers without nesting ConcatValue inside other helpers
'full_name_upper' => Db::concat(Db::upper('first_name'), ' ', Db::upper('last_name')),
'email_lower' => Db::lower('email'),
// Length of concatenation via raw as a necessary fallback
'name_length' => Db::raw('LENGTH(first_name) + 1 + LENGTH(last_name)')
])
->limit(2)
->get();
echo " Combined operations:\n";
foreach ($users as $user) {
echo " • Original: {$user['first_name']} {$user['last_name']}\n";
echo " Full name (UPPER): {$user['full_name_upper']}\n";
echo " Email (lower): {$user['email_lower']}\n";
echo " Name length: {$user['name_length']} characters\n";
}
echo "\n";
// Example 9: Advanced string operations
echo "9. Advanced string operations...\n";
// Demonstrate using library helpers for string manipulation
// All helpers handle dialect-specific differences automatically
$users = $db->find()
->from('users')
->select([
'email',
// Use helpers for string operations
'email_length' => Db::length('email'),
'at_position' => Db::position('@', 'email'),
// Extract first 5 characters using helper
'email_prefix' => Db::substring('email', 1, 5),
// Extract last 10 characters using helper
'email_suffix' => Db::right('email', 10),
// Use greatest() helper to find maximum length between email and first_name
'max_length' => Db::greatest(Db::length('email'), Db::length('first_name'))
])
->get();
foreach ($users as $user) {
echo " • {$user['email']}\n";
echo " Length: {$user['email_length']}, '@' at position: {$user['at_position']}\n";
echo " Prefix (first 5): {$user['email_prefix']}, Suffix (last 10): {$user['email_suffix']}\n";
echo " Max length (email vs name): {$user['max_length']}\n";
}
echo "\n";
// Example 14: REGEXP operations
echo "14. REGEXP operations - Pattern matching and extraction...\n";
$driver = getCurrentDriver($db);
// Check if REGEXP is supported (SQLite requires extension)
if ($driver === 'sqlite') {
try {
$db->rawQuery("SELECT 'test' REGEXP 'test'");
} catch (\PDOException $e) {
echo " ⚠ REGEXP extension not available in SQLite, skipping regexp examples\n";
echo "\nString helper functions example completed!\n";
exit(0);
}
}
// Insert test data with various email formats
$schema = $db->schema();
recreateTable($db, 'contacts', [
'id' => $schema->primaryKey(),
'email' => $schema->text(),
'phone' => $schema->text(),
]);
$db->find()->table('contacts')->insertMulti([
['email' => 'user@example.com', 'phone' => '+1-555-123-4567'],
['email' => 'admin@test.org', 'phone' => '+44-20-7946-0958'],
['email' => 'invalid-email', 'phone' => '12345'],
]);
// REGEXP_MATCH - Find valid email addresses
echo " a) REGEXP_MATCH - Find valid email addresses:\n";
$validEmails = $db->find()
->from('contacts')
->select(['email'])
->where(Db::regexpMatch('email', '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'))
->get();
foreach ($validEmails as $contact) {
echo " • {$contact['email']}\n";
}
echo "\n";
// REGEXP_REPLACE - Format phone numbers
echo " b) REGEXP_REPLACE - Format phone numbers:\n";
$formattedPhones = $db->find()
->from('contacts')
->select([
'phone',
'formatted' => Db::regexpReplace('phone', '-', ' ')
])
->where(Db::regexpMatch('phone', '-'))
->get();
foreach ($formattedPhones as $contact) {
echo " • {$contact['phone']} → {$contact['formatted']}\n";
}
echo "\n";
// REGEXP_EXTRACT - Extract domain from email
echo " c) REGEXP_EXTRACT - Extract domain from email:\n";
$domains = $db->find()
->from('contacts')
->select([
'email',
'domain' => Db::regexpExtract('email', '@([a-zA-Z0-9.-]+\\.[a-zA-Z]{2,})', 1)
])
->where(Db::regexpMatch('email', '@'))
->get();
foreach ($domains as $contact) {
if ($contact['domain'] !== null) {
echo " • {$contact['email']} → domain: {$contact['domain']}\n";
}
}
echo "\n";
echo "\nString helper functions example completed!\n";