PHP-正则表达式,用于从行中删除域名

时间:2019-03-05 07:22:34

标签: php regex

我正在从数据库中获取很多产品行。

其中某些行包含一个域名(例如google.com),在输出之前,我希望将其从字符串中删除(修剪)。 注意:有多个TLD(.se,.fi。,。net,.org ...)

首先,我将从域表中获取所有域名到自己的数组中,然后使用editor.ui.registry.create() editor.ui.Factory.create() editor.ui.create() tinymce.ui.registry.create() tinymce.ui.Factory.create() tinymce.ui.create() ,运行测试该字符串是否包含特定域。如果在产品行中未找到域,则无需修剪任何内容。

这是domains数组的样子:

preg_match()

这是从数据库输出的行的示例:

[0] => Array
        (
            [domain] => google.com
        )
 [1] => Array
        (
            [domain] => google.se
        )

下面是我到目前为止所尝试的:

Product 1 - Test purposes 1
Product 2 - Test purposes 2 google.com
Product 2 - Test purposes 2 google.se

这会忽略它找到的所有域,仅使用原始的<?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']; } } } 而不是从$row['product']修剪域名。

2 个答案:

答案 0 :(得分:2)

这里是一种方法,只需将$ 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;
}

答案 1 :(得分:1)

摘要

这是一个美丽的。您会喜欢答案的。

} else {之前添加以下行:

continue 2;

说明

由于您正在执行双循环,如果匹配的域不是最后一个域,它将覆盖 did 匹配的域。因此,一旦找到匹配项,您就需要直接进入下一个,而不仅仅是下一个 domain

代码

<?php

$domains = [
    ["domain" => "google.com"],
    ["domain" => "google.se"]
];

$rows = [
    ["product" => "Product 1 - Test purposes 1"],
    ["product" => "Product 2 - Test purposes 2 google.com"],
    ["product" => "Product 2 - Test purposes 2 google.se"],
];

$table = [];

# loop through all rows from the database
foreach($rows as $id => $row){
    # 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[$id]['product'] = $trimmed;
            continue 2;
            //As soon as you hit a match, go to the next *row*.
            //Don't try to match any more domains.
        } else {
            $table[$id]['product'] = $row['product'];
        }
    }
}

var_dump($table);

注意事项

这假设您每行只有一个一个域匹配项。

https://3v4l.org/Oo2Ie