preg_replace 在 [link] 和 [/link] 之间用 hyperlink 替换 url 但 link 不能包含 ?要么 ()
preg_replace replaces url with hyperlink between [link] and [/link] but link can't cotain ? or ()
我的代码:
preg_match_all('(\[(link)\](.*?)\[/(link)\])', $message, $matches);
$matches = $matches[2];
foreach($matches as $match){
//CHECK LINK AND VERIFY
$message = preg_replace('(\[(link)\]('.$match.')\[/(link)\])', '<a href="'.$match.'" target="_blank">'.$match.'</a>', $message);
}
如您所见https://mcskripts.dk/forum/id/286
该脚本有效,但无法替换包含 () 或 ?
的链接
我能解决这个问题吗?
对不起,如果我重新发布,只是不知道我是否可以评论旧帖子并得到回复。
您可以使用单个 preg_replace:
$message = preg_replace('~\[link\](.+?)\[/link\]~', '<a href="" target="_blank"></a>', $message);
如果要在替换之前验证链接,请使用 preg_replace_callback:
$message = preg_replace_callback(
'~\[link\](.+?)\[/link\]~',
function($match) {
# call your function to validate the link
if (validate_link($match[1])) {
return '<a href="'.$match[1].'" target="_blank">'.$match[1].'</a>';
} else {
return 'What you want when validation fail!';
}
},
$message
);
我的代码:
preg_match_all('(\[(link)\](.*?)\[/(link)\])', $message, $matches);
$matches = $matches[2];
foreach($matches as $match){
//CHECK LINK AND VERIFY
$message = preg_replace('(\[(link)\]('.$match.')\[/(link)\])', '<a href="'.$match.'" target="_blank">'.$match.'</a>', $message);
}
如您所见https://mcskripts.dk/forum/id/286 该脚本有效,但无法替换包含 () 或 ?
的链接我能解决这个问题吗?
对不起,如果我重新发布,只是不知道我是否可以评论旧帖子并得到回复。
您可以使用单个 preg_replace:
$message = preg_replace('~\[link\](.+?)\[/link\]~', '<a href="" target="_blank"></a>', $message);
如果要在替换之前验证链接,请使用 preg_replace_callback:
$message = preg_replace_callback(
'~\[link\](.+?)\[/link\]~',
function($match) {
# call your function to validate the link
if (validate_link($match[1])) {
return '<a href="'.$match[1].'" target="_blank">'.$match[1].'</a>';
} else {
return 'What you want when validation fail!';
}
},
$message
);