2012-06-01 31 views
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 
'; 

?> 

所以基本上,我想linkify文本網址沒有包裹在<一個> </A >並添加目標=「_空白」,以那些。的preg_replace鏈接與一些例外

任何人都可以幫助我嗎?

+0

這可能不是一個任務適合正則表達式 - 我建議標準字符串方法,如以及庫函數來識別URL,因爲正則表達式會很難做到完全正確。 – Nightfirecat

回答

0

首先,我會用一些XML/HTML處理庫,以獲得標籤之間的文本,然後使用簡單的regex:

PHP validation/regex for URL

讓所有的URL的鏈接。

1

這將增加所述目標:

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

這是檢測網址和使它們爲鏈接(這是脆)的粗方式:

$string = preg_replace("/(http[^\ ]+)/", "<a href=\"$1\" target=\"_blank\">$1</a>", $string); 
0
$result = preg_replace(
    "/(?<![\>https?:\/\/|href=\"'])(?<http>(https?:[\/][\/]|www\.)([a-z]|[A-Z]|[0-9]|[\/.&?= ]|[~])*)/", 
    "<a href=\"$1\">$1</a>", 
    $string 
); 
2
$string = preg_replace("/<a(.*?)>/", "<a$1 target=\"_blank\">", $string); 

此將增加一個額外的target=\"_blank\",因爲它已經設置。

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

這將確保只有一個target="_blank"在URL中加入

例如: - http://www.phpliveregex.com/p/6qG