I'm fetching a lot of product rows from the database.
Some of these rows contains a domain name (eg. google.com) which I'd like to be removed (trim) from the string before outputting it. NOTE: There are multiple TLD's (.se, .fi., .net, .org ...)
At first, I will fetch all domain names from domain table into own array and then with preg_match(), run a test whether the string contains a specific domain or not. If domain is not found from product row, nothing needs to be trimmed.
Here's what the domains array will look like:
[0] => Array
(
[domain] => google.com
)
[1] => Array
(
[domain] => google.se
)
Here's an example of rows outputted from the database:
Product 1 - Test purposes 1
Product 2 - Test purposes 2 google.com
Product 2 - Test purposes 2 google.se
And underneath is what I've tried so far:
<?php
...
$table = [];
# loop through all rows from the database
while ($row = $stmt->fetch()) {
# loop through all domains
foreach($domains as $domain) {
if(preg_match("/{$domain['domain']}/i", $row['product'],$matches, PREG_OFFSET_CAPTURE)) {
$trimmed = str_replace($domain['domain'], '', $row['product']) ;
$table[$i]['product'] = $trimmed;
} else {
$table[$i]['product'] = $row['product'];
}
}
}
This does ignore all the domains it finds and just uses the original $row['product'] instead of trimming the domain name from the $row['product'].
$row['product'], it returns the original.