Reputation: 904
I am looking for a php way to search for a string of text and turn the text within that string to a link.
n being numbers 1-9
Jnn:nn:nn:nn
The link bit would look like this
<a href='http://juno.astroempires.com/map.aspx?loc=Jnn:nn:nn:nn'>Jnn:nn:nn:nn</a>
Hope this makes sense. I know its possible but I don't know how to do it.
This is the final solution I came up with because I integrated into an existing function, thanks for the idea tho bumperbox and the edit Tobiask
function makeClickableLinks($text){
$text = html_entity_decode($text);
$text = " ".$text;
$text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
'<a href="\\1" target=_blank>\\1</a>', $text);
$text = eregi_replace('(((f|ht){1}tps://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
'<a href="\\1" target=_blank>\\1</a>', $text);
$text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
'\\1<a href="http://\\2" target=_blank>\\2</a>', $text);
$text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})',
'<a href="mailto:\\1" target=_blank>\\1</a>', $text);
$text = eregi_replace('(J[0-9]{2}):([0-9]{2}):([0-9]{2}):([0-9]{2})',
'<a href="http://juno.astroempires.com/map.aspx?loc=\\1:\\2:\\3:\\4" target=_blank>\\1:\\2:\\3:\\4</a>', $text);
return $text;
}
This is used in a ajax / mysql chat system. I did have this done by jQuery but its less for the user to do if I just store the links.
Upvotes: 0
Views: 201
Reputation: 1254
using the regex engine is totally overkill for that. Why not try something like this:
$url_base = 'http://juno.astroempires.com/map.aspx';
$loc = 'Jnn:nn:nn:nn';
$parameters = array('loc' => $loc);
$url = sprintf('<a href="%s">%s</a>', $url_base.'?'.http_build_query($parameters), $loc);
// do whatever you need with $url
echo $url;
Upvotes: 1
Reputation: 10214
look at preg_replace
http://php.net/manual/en/function.preg-replace.php
i haven't tested this but it should be pretty close
$str = preg_replace("/(J\d{2}:\d{2}:\d{2}:\d{2})/s", "<a href="{$1}">{$1}</a>", $str);
\d matches a digit {2} means 2 digits
{$1} = everything that was matched inside the first set of ( )
Upvotes: 2