2012-05-20 2 views
4

나는 PHP에서 preg_replace이다 기능을 사용하고 사용자가 bit.ly 단축 링크와 함께 제출 URL을 대체하기 위해 노력하고 있습니다 :대체 된 텍스트를 preg_replace로 어떻게 가져올 수 있습니까?

$comment = preg_replace('/(http|ftp)+(s)?:(\/\/)((\w|\.)+)(\/)?(\S+)?/i', '', $strText); 

이는 주석을 표시하고 URL을 "쓸어"됩니다. 질문은 어떻게 URL에서 텍스트를 가져와 나중에 추가 할 수 있습니까? php.net에서

답변

3

preg_replace_callback()

예 :

<?php 
// this text was used in 2002 
// we want to get this up to date for 2003 
$text = "April fools day is 04/01/2002\n"; 
$text.= "Last christmas was 12/24/2001\n"; 
// the callback function 
function next_year($matches) 
{ 
    // as usual: $matches[0] is the complete match 
    // $matches[1] the match for the first subpattern 
    // enclosed in '(...)' and so on 
    return $matches[1].($matches[2]+1); 
} 
echo preg_replace_callback(
      "|(\d{2}/\d{2}/)(\d{4})|", 
      "next_year", 
      $text); 

?> 

이 URL을 대체하는 콜백 함수를 정의합니다. 일치 항목을 매개 변수로 수신하고 일치 항목에 따라 대체 문자열을 작성합니다.