Jump to content

Str_Replace on Both Ends


nick.ginsberg

Recommended Posts

Hello all,I'm working on a coding project. What I need to do is take a certain part of the text and add something to the beginning and end (more specifically, html tags). Basically what I want to do is that given a paragraph of text, if there is a URL within that paragraph to add link tags to the beginning and end. Here is an example. Say someone goes to post this:You should go to www.google.com because it is a great website.I would like www.google.com to automatically be put in between URL tags. I can do something along the lines of str_replace("http://www.","<a href='http://www.'",$post), but that will only put the tag in the front--i need a way to close them. I've been told to use preg_replace somehow but I'm not sure how that is done.Thanks.Nick

Link to comment
Share on other sites

function createTextLinks($str='') {  if($str=='' or !preg_match('/(http|www\.|@)/im', $str)){  return $str; }  // replace links: $str = preg_replace("/([ \t]|^)www\./im", "\\1http://www.", $str); $str = preg_replace("/([ \t]|^)ftp\./im", "\\1ftp://ftp.", $str);  $str = preg_replace("/(https?:\/\/[^ )\r\n!]+)/eim", "'<a href=\"\\1\" title=\"\\1\">\\1</a>'", $str);  $str = preg_replace("/(ftp:\/\/[^ )\r\n!]+)/eim", "'<a href=\"\\1\" title=\"\\1\">\\1</a>'", $str);  $str = preg_replace("/([-a-z0-9_]+(\.[_a-z0-9-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)+))/eim", "'<a href=\"mailto:\\1\" title=\"Email \\1\">\\1</a>'", $str);  $str = preg_replace("/(\&)/im","\\1amp;", $str);  return $str;}

2min google

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...