Jump to content

Recommended Posts

Hi,

 

I have a string containing html markup. I'm trying to make links in it clickable (for when it is displayed in the browser). This is what I have so far:

 

 

  $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
    '<a target="_blank" href="\\1">\\1</a>', $text);

  $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
    '\\1<a target="_blank" href="http://\\2">\\2</a>', $text);

  $text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})',
    '<a href="mailto:\\1">\\1</a>', $text);

 

The problem is that this obviously matches urls in (for example) image tags. I guess I only want to be matching urls that are not inside < > tags. My first though was something like >[^<]* at the beginning - that should match a closing angle bracket followed by zero or more characters which aren't opening angle brackets, right? Would that work?

 

Link to comment
https://forums.phpfreaks.com/topic/122301-hyperlinking-urls/
Share on other sites

<pre>
<?php
$data = <<<DATA
<img src="http://www.somewhere.com/image.jpg">
Visit www.phpfreaks.com!
<a href="http://www.google.com">http://www.google.com</a>
See http://www.regular-expressions.info
DATA;
$pieces = preg_split('/(<[^>]+>)/', $data, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$num_pieces = count($pieces);
for ($i = 0; $i < $num_pieces; $i++) {
	### Skip tags or content of <a>.
	if (substr($pieces[$i], 0, 1) == '<'
	||  array_key_exists($i-1, $pieces)
	&&  substr($pieces[$i-1], 0, 3) == '<a '
	){
		continue;
	}
	$pieces[$i] = preg_replace('%
		(
			(?:
				(??:https?|ftp)://)
				|
				www\.
			)
			\S+
			(?<!\p{P})
		)
	%x', '<a href="$1">$1</a>', $pieces[$i]);
}
echo htmlspecialchars(join('', $pieces));
?>
</pre>

Link to comment
https://forums.phpfreaks.com/topic/122301-hyperlinking-urls/#findComment-631958
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.