php - 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']
.
解决方案
这是一种方法,只需将 $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;
}
推荐阅读
- r - 在侧边栏列上插入空格或中断 - Flexdashboard
- r - 如何在 r 中使用固定时间效果?
- r - 有没有办法加载多个 .txt 文件并在之后列出它们以便可以更改编码?
- javascript - 我可以在 Typescript 中使用 io-ts 使用正则表达式测试字符串吗
- c# - 如何使用 ManagementObjectSearcher 欺骗 HWID 数据?
- sql - 为什么我收到错误消息:ORA-01861:从教科书复制时文字与格式字符串不匹配
- r - 将 stat_function 与具有多个级别的因子的回归一起使用
- html - 是否可以通过 webrtc 或其他方式从浏览器发送大型视频文件(大于 4 Gig)并通过 HLS 或其他格式进行流式传输?
- c - 为什么我的简单 makefile 只打印规则?
- windows - 让 Graphic Magick 检测 Ghostscript 以在 Windows 上阅读 pdf。如何将 WINDOWS CMD 上的 Ghostscript 调用名称更改为“gs”?