2 回答
TA贡献1853条经验 获得超6个赞
为此,我将preg_replace_callback
捕获 中的文本[]
、slug 类型(user
、career
或business
)和值(对于 slug user
)分组,并将它们传递到回调以形成 URL:
$Rtm = '@[ Test Career 12](career:235)@[ Testing11](business:2)@[ Username](user:1)some text';
$Rtm = preg_replace_callback('/@\[([^]]*)\]\(([a-z]+):([^)]*)\)/', function ($match) {
switch($match[2]) {
case 'user':
return "<a href=\"/en/main/profile_page_link/$match[3]\">$match[1]</a>";
break;
case 'business':
return "<a href=\"/en/business/1/about\">$match[1]</a>";
break;
case 'career':
return "<a href=\"/en/main/2/about\">$match[1]</a>";
break;
default:
return "";
break;
}
}, $Rtm);
echo $Rtm;
输出(对于您的输入字符串):
<a href="/en/main/2/about"> Test Career 12</a><a href="/en/business/1/about"> Testing11</a><a href="/en/main/profile_page_link/1"> Username</a>some text
TA贡献1859条经验 获得超6个赞
使用@\[([^][]*?)\]
而不是@\[(.*?)\]
演示和解释。
rtrim
所有更换后仅执行一次。
$Rtm = '@[ Test Career 12](career:235)@[ Testing11](business:2)@[ Username](user:1)some text';
if (preg_match("/@\[([^][]*?)\]\(user:(.*?)\)/", $Rtm, $match)) {
$Rtm = preg_replace("/@\[([^][]*?)\]\(user:(.*?)\)/", '<a href="/en/main/profile_page_link/$2">$1</a>, ', $Rtm);
}
if (preg_match("/@\[([^][]*?)\]\(business:(.*?)\)/", $Rtm, $match)) {
$Rtm = preg_replace("/@\[([^][]*?)\]\(business:(.*?)\)/", '<a href="/en/business/$2/about">$1</a>, ', $Rtm);
}
if (preg_match("/@\[([^][]*?)\]\(career:(.*?)\)/", $Rtm, $match)) {
$Rtm = preg_replace("/@\[([^][]*?)\]\(career:(.*?)\)/", '<a href="/en/main/$2/about">$1</a>, ', $Rtm);
}
$Rtm = rtrim($Rtm, ', ');
echo $Rtm;
- 2 回答
- 0 关注
- 159 浏览
添加回答
举报