1
<?php
// I have a string, something like this:
$string = '
    Lorep ipsum <a href="http://www.example.com">example</a> lorem ipsum
    lorem ipsum http://www.example.com/index.php?param1=val&param2=val lorem ipsum
';
// I need to do some magick with preg_replace and get string like this:
$string = '
    Lorep ipsum <a href="http://www.example.com" target="_blank">example</a> lorem ipsum
    lorem ipsum <a href="http://www.example.com/index.php?param1=val&param2=val" target="_blank">http://www.example.com/index.php?param1=val&param2=val</a> lorem ipsum
';

?>

So basicly, I want to linkify URLs in text that are not wrapped in <a></a> and add target="_blank" to those that are.

Can anyone help me with this?

Tomas Žeimys
  • 11
  • 1
  • 3
  • This is probably not a task suitable for regex - I'd suggest standard string methods, as well as library functions to identify URLs, since regular expressions will strain to do that entirely correctly. – Nightfirecat Jun 01 '12 at 06:47

4 Answers4

2
$string = preg_replace("/<a(.*?)>/", "<a$1 target=\"_blank\">", $string);

this will add an extra target=\"_blank\" incase it is already set.

$string = preg_replace("/<a (href=".*?").*?>/", "<a $1 target="_blank">", $string);

this will make sure that only one target="_blank" is added in the URL

example:- http://www.phpliveregex.com/p/6qG

Rohan
  • 35
  • 1
  • 9
1

This will add the target:

$string = preg_replace("/<a(.*?)>/", "<a$1 target=\"_blank\">", $string);

This is a crude way of detecting URLs and making them into links (this is brittle):

$string = preg_replace("/(http[^\ ]+)/", "<a href=\"$1\" target=\"_blank\">$1</a>", $string);
Ansari
  • 8,168
  • 2
  • 23
  • 34
0

First, I would use some XML/HTML processing library, to get text between tags, then using simple regex:

PHP validation/regex for URL

make all URLs as links.

Community
  • 1
  • 1
sirex
  • 4,593
  • 2
  • 32
  • 21
0
$result = preg_replace(
  "/(?<![\>https?:\/\/|href=\"'])(?<http>(https?:[\/][\/]|www\.)([a-z]|[A-Z]|[0-9]|[\/.&?= ]|[~])*)/",
  "<a href=\"$1\">$1</a>",
  $string
);
j0k
  • 22,600
  • 28
  • 79
  • 90