2011-10-04 83 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;