忽略PHP正则表达式中的url
我有一个实用程序,我试图在一个应用程序中强制执行品牌标准,在这个应用程序中,函数将用一个类将品牌词包装在一个范围内忽略PHP正则表达式中的url,php,regex,preg-match-all,Php,Regex,Preg Match All,我有一个实用程序,我试图在一个应用程序中强制执行品牌标准,在这个应用程序中,函数将用一个类将品牌词包装在一个范围内 public function filterBrandWords($text) { // look up the brand words from the config settings $filter_terms = ['brandword1', 'brandword2', 'brandword3']; $filtered_
public function filterBrandWords($text)
{
// look up the brand words from the config settings
$filter_terms = ['brandword1', 'brandword2', 'brandword3'];
$filtered_text = $text;
foreach ($filter_terms as $word) {
$match_count = preg_match_all('/' . $word . '/i', $text, $matches);
for ($i = 0; $i < $match_count; $i++) {
$brand_string = trim($matches[0][$i]);
$lower = strtolower($brand_string);
$new = '<span class="font-semibold">' . substr($lower, 0, 3) . '</span>' . substr($lower, 3);
$filtered_text = preg_replace('/\b' . $brand_string . '\b/', $new, $filtered_text);
}
}
return $filtered_text;
}
输出是
<span class="font-semibold">bra</span>ndword1
<span class="font-semibold">bra</span>ndword1.com
brandword1
通过URL,输出是
<span class="font-semibold">bra</span>ndword1
<span class="font-semibold">bra</span>ndword1.com
brandword1.com
在这些情况下,我想忽略过滤器,直接说出来。如果你想忽略像URL这样的东西,你可以用下面这样的东西作为你的正则表达式:
(?|.*\.(com|net|org))
这是一个消极的前瞻性断言,与URL的(广义)匹配。正如我在这里所做的那样,将其插入到函数中:
function filterBrandWords($text)
{
// look up the brand words from the config settings
$filter_terms = ['brandword1', 'brandword2', 'brandword3'];
$filtered_text = $text;
if(!preg_match('/(?|.*\.(com|net|org))/', $filtered_text)) { // if it resembles a URL, skip it
foreach ($filter_terms as $word) {
$match_count = preg_match_all('/' . $word . '/i', $text, $matches);
for ($i = 0; $i < $match_count; $i++) {
$brand_string = trim($matches[0][$i]);
$lower = strtolower($brand_string);
$new = '<span class="font-semibold">' . substr($lower, 0, 3) . '</span>' . substr($lower, 3);
$filtered_text = preg_replace('/\b' . $brand_string . '\b/', $new, $filtered_text);
}
}
}
return $filtered_text;
}
然后返回整个URL:
brandword1.com
您能与我们分享一些示例输入和您期望的输出吗?刚刚更新了帖子以反映Thoselso@JayBlanchard我喜欢您在网站上使用Charles Rennie Mackintosh字体:)您一直在谈论URL,但您在这里向我们展示的内容中没有URL。如果我使用brandword1.com,这就是上面的输出