2017-02-03 6 views
0

일부 코드를 작성 중이므로 진행할 수있는 충분한 작업을 수행했습니다. 해당 텍스트 본문 내의 이미지 URL과 웹 링크를 교체하고 싶습니다.PHP preg_match 및 preg_replace 텍스트 (url 및 image 태그 사용)

EG는

가 교체 "이것은 내 http://www.google.com 텍스트와 http://www.somewebimage.png 일부 이미지입니다"

내 해킹 URL을 대체하기 위해 저를 얻는다 (들) "이것은 내 <a href="http://www.google.com">http://www.google.com</a> 텍스트와 <img src="http://www.somewebimage.png"> 일부 이미지입니다" 나는 $ reg_exUrl 코드 블록을 차단하는 경우 또는 IMG 링크가 아닌 both..one는 이상 그것은 내가 URL 링크를 얻을 실행하는 경우 나 이미지 링크를 얻을 수 있기 때문에 순서

$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; 
$reg_exImg = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?(jpg|png|gif|jpeg)/'; 
$post = "This is my text with http://www.google.com and some image http://www.somewebimage.png"; 

if(preg_match($reg_exImg, $post, $img)) { 
    $img_post = preg_replace($reg_exImg, "<img src=".$img[0]." width='300' style='float: right;'> ", $post); 
} else { 
    $img_post = $post; 
} 
if(preg_match($reg_exUrl, $post, $url)) { 
    $img_post = preg_replace($reg_exUrl, "<a href=".$url[0]." target='_blank'>{$url[0]}</a> ", $post); 
} else { 
    $img_post = $post; 
} 

의 기록됩니다.

+0

가 난 할 노력하고있어하기와 패턴을 테스트 URL이 링크와 IMG의 URL이 포함되어 있습니다 간단한 공급 .. –

+0

우선입니다 : preg_replace_callback를 사용하여, 당신은 콜백 함수의 대체 문자열을 선택할 수 있습니다 preg_replace와 함께 사용하기 전에'preg_match'는 쓸모가 없습니다. –

+0

두 경우에 하나의 패턴을 사용해야하고,'preg_replace_callback'을 사용하여 대체 마스크를 선택해야합니다. 이 방법은 모두 한 번에 완료되며 아무 것도 덮어 쓰지 않습니다. 콜백 함수에서'parse_url'과'explode'를 사용하여 쉽게 파일 확장자를 추출 할 수 있습니다. –

답변

0

두 번 패턴을 매우 비슷하게 처리 할 수 ​​있으므로 두 가지 경우를 처리하는 패턴을 쉽게 만들 수 있습니다.

$post = "This is my text with http://www.google.com and some image http://www.domain.com/somewebimage.png"; 

# the pattern is very basic and can be improved to handle more complicated URLs 
$pattern = '~\b(?:ht|f)tps?://[a-z0-9.-]+\.[a-z]{2,3}(?:/\S*)?~i'; 
$imgExt = ['.png', '.gif', '.jpg', '.jpeg']; 
$callback = function ($m) use ($imgExt) { 
    if (false === $extension = parse_url($m[0], PHP_URL_PATH)) 
     return $m[0]; 

    $extension = strtolower(strrchr($extension, '.')); 

    if (in_array($extension, $imgExt)) 
     return '<img src="' . $m[0] . '" width="300" style="float: right;">'; 
    # better to do that via a css rule --^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
    return '<a href="' . $m[0] . '" target="_blank">' . $m[0] . '</a>'; 
}; 

$result = preg_replace_callback($pattern, $callback, $post); 
+0

좋은 일을했습니다. 예, 할 수있는 방법이 하나 뿐이라는 것을 알았습니다. –