How to limit my regex that is detecting too much? -
i have regex attempting detect title & link markup:
[title](http://link.com)
so far have:
(\[)(.*?)(\])(\(((http[s]?)|ftp):\/\/)(.*?)(\))
which detecting when untitled link markup before it
[http://google.com] [digg](http://digg.com) [internal page] random other text [digg](http://digg.com)
how can limit regex titled link?
full php titled & untitled links:
// 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 );
if you're trying go through markdown links, you'll want grab regex , logic straight source:
https://github.com/michelf/php-markdown/blob/lib/michelf/markdown.php#l510
https://github.com/tanakahisateru/js-markdown-extra/blob/master/js-markdown-extra.js#l630
Comments
Post a Comment