Regular Expressions 101

Community Patterns

匹配html中的关键词

1

Regular Expression
PCRE (PHP <7.3)

/
<([a-zA-Z\d]+?)([^<>]|(?!.*href).*)>([^<>]*?)(小编)([^<>]*?)(<\/\1>)
/
gm

Description

排除掉标签中带href的 php使用方法 /** * 将HTML中的关键词 替换为关键词链接 * @param string $html 处理的html * @param array $keyWord 关键词数组 * @param array $link 链接数组 * @param int $changeNum 同一关键词替换次数 * @param bool $newWindow 链接是否新窗口打开 * @return string|string[]|null */ public function linkKeyword($html, array $keyWord, array $link, $changeNum = 1, $newWindow = true) { $re = '/<([a-zA-Z\d]+?)([^<>]|(?!.*href).*)>([^<>]*?)({key})([^<>]*?)(<\/\1>)/m'; $con = $newWindow ? '<$1$2>$3<a href="{link}" target="_blank">$4</a>$5$6' : '<$1$2>$3<a href="{link}">$4</a>$5$6'; $regex = $cons = []; foreach ($keyWord as $key => $item) { $regex[] = str_replace('{key}', $item, $re); $cons[] = str_replace('{link}', $link[$key], $con); } return preg_replace($regex, $cons, $html, $changeNum); }

Submitted by anonymous - 4 years ago