PHP正则替换伪链接:区分文本前后链接的HTML样式
伪链接分类替换解决方案
需求说明
需将文本开头所有格式为a[链接内容](含a [链接内容]变体,支持逗号、空格分隔)的伪链接,替换为带style1类的<a>标签;文本主体内容之后的同格式伪链接,替换为带style2类的<a>标签。
原始文本示例
a[link], a[link] a [link] text text text a [link] text a[link] text
已尝试的PHP代码
<?php $re = '/^(a\[(\w+[\s+]?)+\],?\s?)+/iu'; $str = 'a[link], a[link] a[link] text text text a[link] text a[link] text'; preg_match($re, $str, $matches, PREG_OFFSET_CAPTURE, 0); var_dump($matches); ?>
预期转换效果
完善实现方案
核心思路:先拆分文本为「开头链接区块」和「剩余文本」两部分,再分别对两部分的伪链接做针对性替换。
最终PHP代码
<?php $str = 'a[link], a[link] a [link] text text text a [link] text a[link] text'; // 匹配开头连续的伪链接区块(支持a[xxx]、a [xxx]格式,允许逗号+空格分隔) $startLinkPattern = '/^(?:a\s?\[.*?\](?:,\s?)?\s?)+/iu'; preg_match($startLinkPattern, $str, $matches, PREG_OFFSET_CAPTURE); $processedStr = ''; if (!empty($matches)) { $startBlock = $matches[0][0]; $startEndPos = $matches[0][1] + strlen($startBlock); // 替换开头区块的伪链接为style1类,并清理多余逗号和空格 $style1Replaced = preg_replace('/a\s?\[([^\]]+)\]/iu', '<a href="$1" class="style1">$1</a>', $startBlock); $style1Replaced = preg_replace('/\s*,\s*/', '', $style1Replaced); $processedStr .= $style1Replaced; // 替换剩余文本的伪链接为style2类 $remainingText = substr($str, $startEndPos); $style2Replaced = preg_replace('/a\s?\[([^\]]+)\]/iu', '<a href="$1" class="style2">$1</a>', $remainingText); $processedStr .= $style2Replaced; } else { // 无开头链接时,直接替换所有伪链接为style2类 $processedStr = preg_replace('/a\s?\[([^\]]+)\]/iu', '<a href="$1" class="style2">$1</a>', $str); } echo $processedStr; ?>
代码说明
- 开头区块匹配:
^(?:a\s?\[.*?\](?:,\s?)?\s?)+精准匹配文本开头连续的伪链接,兼容空格、逗号分隔的场景。 - 伪链接替换:
a\s?\[([^\]]+)\]匹配单个伪链接并捕获链接内容,支持链接内容含空格的情况。 - 格式清理:开头区块替换后清理多余的逗号和空格,保证输出格式整洁。
内容的提问来源于stack exchange,提问作者Mister_X
相关产品推荐
相关产品推荐

