我有一个正则表达式试图检测标题和链接标记:
[title](http://link.com)
到目前为止,我有:
(\[)(.*?)(\])(\(((http[s]?)|ftp):\/\/)(.*?)(\))
当无标题链接标记在它之前时,它会检测到很多
[http://google.com] [Digg](http://digg.com)
[Internal Page] Random other text [Digg](http://digg.com)
如何将正则表达式限制为标题链接?
有标题和无标题链接的完整 PHP:
// Titled Links
// [Digg](http://digg.com)
// [Google](http://google.com)
$text = preg_replace_callback(
'/(\[)(.*?)(\])(\(((http[s]?)|ftp):\/\/)(.*?)(\))/',
function ($match) {
$link = trim($match[7]);
$ret = "<a target='_blank' href='" . strtolower($match[5]) . "://" . $link . "'>" . trim($match[2]) . "</a>";
if (strtolower($match[5]) == "http") {
$ret .= "<img src='/images/link_http.png' class='link' />";
} else if (strtolower($match[5]) == "https") {
$ret .= "<img src='/images/link_https.png' class='link' />";
} else if (strtolower($match[5]) == "ftp") {
$ret .= "<img src='/images/link_ftp.png' class='link' />";
}
return $ret;
},
$text
);
// Untitled Links
// [Internal Page]
// [http://google.com]
$text = preg_replace_callback(
'/(\[)(.*?)(\])/',
function ($match) {
$link = trim($match[2]);
$ret = "";
if ($this->startsWith(strtolower($link), "https")) {
$ret = "<a target='_blank' href='" . $link . "'>" . $link . "</a>";
$ret .= "<img src='/images/link_https.png' class='link' />";
} else if ($this->startsWith(strtolower($link), "http")) {
$ret = "<a target='_blank' href='" . $link . "'>" . $link . "</a>";
$ret .= "<img src='/images/link_http.png' class='link' />";
} else if ($this->startsWith(strtolower($link), "ftp")) {
$ret = "<a target='_blank' href='" . $link . "'>" . $link . "</a>";
$ret .= "<img src='/images/link_ftp.png' class='link' />";
} else {
$link = str_replace(" ", "_", $link);
$ret = "<a href='" . $link . "'>" . trim($match[2]) . "</a>";
}
return $ret;
},
$text
);