note 64384 deleted from function.preg-grep by bjori
| From: | bjori@php.net | Date: | Thu, 13 Apr 2006 11:21:03 +0000 |
| Subject: | note 64384 deleted from function.preg-grep by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-107975@lists.php.net to get a copy of this message | ||
Note Submitter: rob at marotori dot com
Reason: bad code
----
This is a usefull function to find all link and 'highight them'.
It caters for links that are already wrapped in a tags and simply ignores them. (only highlights
urls and emails that are not already enclosed by an a tag.)
Dirty... but works
<?
function findlinks($string){
# regular expresion to find matches
$href_regex ="<"; // 1 start of the tag
$href_regex .="\s*"; // 2 zero or more whitespace
$href_regex .="a"; // 3 the a of the tag itself
$href_regex .="\s+"; // 4 one or more whitespace
$href_regex .="[^>]*"; // 5 zero or more of any character that is _not_ the end of the
tag
$href_regex .="href"; // 6 the href bit of the tag
$href_regex .="\s*"; // 7 zero or more whitespace
$href_regex .="="; // 8 the = of the tag
$href_regex .="\s*"; // 9 zero or more whitespace
$href_regex .="[\"']?"; // 10 none or one of " or '
$href_regex .="("; // 11 opening parenthesis, start of the bit we want to capture
$href_regex .="[^\"' >]+"; // 12 one or more of any character _except_ our
closing characters
$href_regex .=")"; // 13 closing parenthesis, end of the bit we want to capture
$href_regex .="[\"' >]"; // 14 closing chartacters of the bit we want to
capture
$regex = "/"; // regex start delimiter
$regex .= $href_regex; //
$regex .= "/"; // regex end delimiter
$regex .= "i"; // Pattern Modifier - makes regex case insensative
$regex .= "s"; // Pattern Modifier - makes a dot metacharater in the pattern
// match all characters, including newlines
$regex .= "U"; // Pattern Modifier - makes the regex ungready
# first find and subst out all text area content
preg_match_all($regex, $string, $regs);
# replace all textarea content with a custom tag
$count = "1";
if(is_array($regs["0"])){
foreach($regs["0"] as $tag){
$string = str_replace($tag,"{link-" . $count . "}",$string);
$textarea[] = array("field" => "{link-" . $count .
"}","data" => $tag);
$count++;
}
}
$string = preg_replace("/([\w\.]+)(@)([\S\.]+)\b/i","<font
color=\"#D3C181\"><a href=\"mailto:$0\">$0</a></font>",$string);
$string = preg_replace("/((http(s?):\/\/)|(www\.))([\S\.]+)\b/i","<font
color=\"#D3C181\"><a href=\"http$3://$4$5\"
target=\"_blank\">$2$4$5</a></font>", $string);
# reassemble to handle php code input into text areas
if(is_array($textarea)){
foreach($textarea as $x){
$string = str_replace($x[field],$x[data],$string);
}
}
return $string;
}
?>