2013-10-04 2 views
1

curl로 찍은 페이지의 urls를 바꾸고 이미지 및 링크에 대한 올바른 링크를 추가해야합니다. 내 PHP 컬 코드는 다음과 같습니다preg_replace change href에서 링크

//original links 
<a href="http://host.org"><img src="./sec.png"></a> 
<link href="./styles.css" type="text/css" /> 
<script src="./style.js"></script><br /> 

//fixed SRC path 
<a href="http://host.org"><img src="http://google.com/./sec.png"></a> 
<link href="./styles.css" type="text/css" /> 
<script src="http://google.com/./style.js"></script> 

//fixed HREF path 
<a href="http://google.com//google.com/./sec.png"></a> 
<link href="http://google.com/./styles.css" type="text/css" /> 
<script src="http://google.com/./style.js"></script> 

그러나 링크가있을 때 "는"그것은 모든 링크를 절단 만 HREF 값을 왼쪽 :

<?php 

$result = '<a href="http://host.org"><img src="./sec.png"></a> 
<link href="./styles.css" rel="alternate stylesheet" type="text/css" /> 
<script type="text/javascript" src="./style.js"></script>'; 

echo $result; 
if (!preg_match('/src="https?:\/\/"/', $result)) { 
     $result = preg_replace('/src="(http:\/\/([^\/]+)\/)?([^"]+)"/', "src=\"http://google.com/\\3\"", $result); 
    } 
echo $result; 
if (!preg_match('/href="https?:\/\/"/', $result)) { 
     $result = preg_replace('/href="(http:\/\/([^\/]+)\/)?([^"]+)"/', "href=\"http://google.com/\\3\"", $result); 
    } 
echo $result; 

?> 

출력이다.

//from 
<a href="http://host.org"><img src="./sec.png"></a> 
//to src fix: 
<a href="http://host.org"><img src="http://google.com/./sec.png"></a> 
//ERRRROR when href fix make : 
<a href="http://google.com//google.com/.sec.png"></a> 

모든 신체가 그것을 고칠 수 있습니까? 당신이

답변

4

당신으로 정규 표현식에서이 불필요한 부분을 제거합니다 감사합니다 ([^ /] +)/

그것은 당신의 정규 표현식은 다음 태그의 URL에 모든 방법을 맞게됩니다.

코드 :

$result = preg_replace('/src="(http:\/\/)?([^"]+)"/', "src=\"http://google.com/\\2\"", $result); 
$result = preg_replace('/href="(http:\/\/)?([^"]+)"/', "href=\"http://google.com/\\2\"", $result); 

결과 :

<a href="http://google.com/host.org"><img src="http://google.com/./sec.png"></a> 
<link href="http://google.com/./styles.css" rel="alternate stylesheet" type="text/css" /> 
<script type="text/javascript" src="http://google.com/./style.js"></script> 

그러나! 나는 당신이 정말로 원하는 것이 상대 URL을 절대 URL로 대체하는 방법이라고 생각합니다. 당신은 (는 IF-검사를 생략 할 수 있습니다이 당신과 함께)이 정규 표현식을 사용할 수 있습니다에 대한 :

$result = preg_replace('/src="(?!http:\/\/)([^"]+)"/', "src=\"http://google.com/\\1\"", $result); 
$result = preg_replace('/href="(?!http:\/\/)([^"]+)"/', "href=\"http://google.com/\\1\"", $result); 
+0

감사합니다 !!!!!! – Eugenia