2011-10-04 77 views
1

嗨,我正在開發一個自定義論壇,在我的網站上。我想將網址轉換爲:http://*.domain.com/photos/ {用戶名}/{photo_id}(我應該同時獲取用戶名和photo_id)到直接圖片代碼,以便用戶獲取圖片的網址。解析bbcode中的url

這應該,如果他們把這個網址有或沒有設置高亮來完成:
即:
http://domain.com/photos/musthafa/12345
[URL = HTTP://domain.com/photos/musthafa/12345]我的照片此處鏈接[/ URL]
[URL = HTTP://domain.com/photos/musthafa/12345] http://domain.com/photos/musthafa/12345 [/ URL]

這應被轉換爲< HTML- imge tag src =「url-to_photo-path/photo_id.j_p_g」/>

我試過這個:

$str = "http://www.domain.com/photos/musthafa/12345" 
$str = preg_replace_callback("'\[url=http:\/\/www\.domain\.com\/photos\/(.*?)\](.*?)\[/url\]'i", 'self::parse_photo_url', $str); 

AND 

    $str = preg_replace_callback("#^https?://([a-z0-9-]+\.)domain.com/photos/(.*?)$#", 'self::parse_gpp_photo', $str); 



function parse_photo_url($url){ 
{ 

     $full_url = "http://www.domain.com/" . $url[1]; 
     $url_segs = parse_url($full_url); 
     $path = explode("/", $url_segs['path']); 
     return '<img src="http://www.domain.com/{path-to-the-gallery}/'.$path[2].'/jpg" />'; 
    } 

回答

0

Musthafa。

我不知道,我已經確切地得到了你想要什麼,但請試試這個:

<?php 

$image_url_samples = array(
    "http://domain.com/photos/musthafa/12345", 
    "[url=http://domain.com/photos/musthafa/12345]my photo link here[/url]", 
    "[url=http://domain.com/photos/musthafa/12345]http://domain.com/photos/musthafa/12345[/url]" 
); 

foreach ($image_url_samples as $image_url_sample) 
{ 
    $conversion_result = preg_replace("/^(http:\\/\\/domain.com\\/photos\\/\\w+\\/\\d+)$/i", 
     "<img src=\"\\1.jpg\" alt=\"\\1\" />", $image_url_sample); 
    $conversion_result = preg_replace("/^\\[url=(http:\\/\\/domain.com\\/photos\\/\\w+\\/\\d+)\\](.+)\\[\\/url\\]$/", 
     "<img src=\"\\1.jpg\" alt=\"\\2\" />", $conversion_result); 
    print $conversion_result . "<br />"; 
} 

輸出是:

<img src="http://domain.com/photos/musthafa/12345.jpg" alt="http://domain.com/photos/musthafa/12345" /> 
<br /> 
<img src="http://domain.com/photos/musthafa/12345.jpg" alt="my photo link here" /> 
<br /> 
<img src="http://domain.com/photos/musthafa/12345.jpg" alt="http://domain.com/photos/musthafa/12345" /> 
<br /> 

順便說一句,如果你想不區分大小寫的URL將i修飾符添加到常規模式的末尾(PHP Pattern Modifiers)。

0

基本上我想提取id(在這個例子中是12345),我需要提取圖片url的直接鏈接,這樣用戶應該得到圖片標籤而不是url。

這就是爲什麼我叫

preg_replace_callback function. 

在簡單的話,我被堵在正則表達式匹配我的域名開頭的網址:

http://domain.com/photos{username}/{id} 
OR 
http://www.domain.com/photos{username}/{id}" 
0

你不需要正則表達式。

function buildLink($id, $name){ 

    $html = array(); 
    $html[] = '<img alt="" src="http://www.domain.com/photos/'; 
    $html[] = $name; 
    $html[] = '/'; 
    $html[] = $id; 
    $html[] = '.jpg">'; 

    return implode('', $html); 

} 

$path  = 'http://www.domain.com/photos/musthafa/12345'; 
$path  = rtrim($path, ' /'); 
$path_parts = explode('/', $path); 
$id   = (int) array_pop($path_parts); 
$name  = array_pop($path_parts); 
$img  = buildLink($id, $name); 
echo $img;