05/22: PHP > テキストにリンク(href)を自動でつける
Category: Web dev
Posted by: hajime osako
function autoLink($str){ $prefix = "([[:space:]]|\(|^)"; $suffix = "([[:space:]]|\))"; $linkPtns = array(); $linkPtns[] = array("([-a-z0-9_.]+@[-a-z0-9_.]+)", "\\1\\2\\3"); $linkPtns[] = array("(http://|https://|ftp://)([[:alnum:]\+\$\;\?\.%,!#~*/:@&=_-]+)", "\\1\\2\\3\\4"); $linkPtns[] = array("(www\.[[:alnum:]\+\$\;\?\.%,!#~*/:@&=_-]+)", "\\1\\2\\3"); $linkPtns[] = array("([[:alnum:]/_-]+)(\.jpg|\.gif|\.png)", "\\1\\4"); foreach($linkPtns as $patterns) { $str = eregi_replace($prefix.$patterns[0].$suffix, $patterns[1], $str); } return $str; } //不正な記号をHTML特殊文字(html entity)に変換する function allHtmlentities($str) { // somehow can't convert em dash and en dash... $new_string = preg_replace( '/([^\x09\x0A\x0D\x20-\x7F]|[\x3A-\x40])/e', '"".ord("$0").";"', $str); return $new_string; }