首页 > 解决方案 > PHP - regular expression to remove domain name from row

问题描述

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'].

标签: phpregex

解决方案


这是一种方法,只需将 $multi 变量设置为您正在使用的任何内容....

// (?) could have more than one domain match true / false

$multi = FALSE;

while ( $row = $stmt->fetch ( ) )
{
    // loop through all domains

    $trimmed = $row['product'];

    foreach ( $domains as $domain )
    {
        if( preg_match ( "/{$domain['domain']}/i", $trimmed ) )
        {
            $trimmed = str_replace ( $domain['domain'], '', $trimmed );

            if ( $multi === FALSE )
            {
                break;
            }
        }
    }

    $table[$i]['product'] = $trimmed;
}

推荐阅读