2012-09-22 4 views
0

간단한 작업을 수행하고 싶습니다. 문자열의 일부 (HTML 파일)에서 코드의 특정 부분을 추출합니다. 예를 들어문자열의 하위 문자열을 모두 가져옵니다.

:

//Get a string from a website: 
$homepage = file_get_contents('http://mywebsite.org'); 

//Then, search a particulare substring between two strings: 
echo magic_substr($homepage, "<script language", "</script>"); 

//where magic_substr is this function (find in this awesome website): 
function magic_substr($haystack, $start, $end) { 

    $index_start = strpos($haystack, $start); 
    $index_start = ($index_start === false) ? 0 : $index_start + strlen($start); 

    $index_end = strpos($haystack, $end, $index_start); 
    $length = ($index_end === false) ? strlen($end) : $index_end - $index_start; 

    return substr($haystack, $index_start, $length); 
} 

내가 싶어 출력,이 경우, 페이지의 모든 스크립트. 그러나 제 경우에는 첫 번째 스크립트 만 얻을 수 있습니다. 나는 재귀가 없기 때문에 그것이 옳다고 생각한다. 그러나 나는 이것을하는 가장 좋은 방법이 무엇인지 모른다! 어떤 제안?

+6

강아지는 무섭게 당신이 [DOM 파서]를 사용하지 않는 때마다 스탬프 (http://php.net/manual/en/book.dom.php) 물건을 찾기 위해 html 문서에서. – moonwave99

+0

안녕하세요. 나는 "max_nested_level"문제가있는 Simple Dom Parser로 시도했다. 그래서이 방법으로 움직였다 :) – alessandronos

+0

max_nested_level의 문제점은 무엇인가? 나는 PHP Simple HTML Dom Parser가 그렇게 할 수 있다고 믿는다. – raygo

답변

0

dom-tree에서 요소를 가져 오는 Prototype/jQuery와 같은 방법이 좋습니다.

jQuery-like interface for PHP에서 시도해보십시오. 나는 PHP에서 그것을 시도하지 않는다.

편집 :

유효한 HTML/XML을 위해 노력 Tidy 또는 HTML Purifier 또는 htmlLawled.

+0

나는 반드시 시도 할 것이다! 고맙습니다! – alessandronos

1

것은이 귀하의 경우에는 어떤주는 태그 또는 데이터 에서
추출기 ($ 홈페이지, "스크립트 언어"스크립트 ") 데이터를 추출하려고,
된 기회가 제대로 스크립트 태그를 보여주는 아니에요을하지만, 사용자가 정의한대로 정의 귀하의 예제에서

/*****************************************************************/ 
/* string refine_str($str,$from,$to="")       */ 
/* show data between $from and $to and also remove $from and $to */ 
/* if $to is not provided $from will be considered    */ 
/* a string to remove.           */ 
/*****************************************************************/ 

function extractor($str,$from,$to) 
{ 
    $from_pos = strpos($str,$from); 
    $from_pos = $from_pos + strlen($from); 
    $to_pos = strpos($str,$to,$from_pos);// to must be after from 
    $return = substr($str,$from_pos,$to_pos-$from_pos); 
    unset($str,$from,$to,$from_pos,$to_pos);   
    return $return; 

}  
+0

그것은 "내"함수와 같습니다 : DI는 $ 문자열과 $ 문자열 사이에있는 첫 번째 문자열 만 볼 수 있습니다.이 경우에는 19 개의 일치 유형이 있어야합니다 .. 나는 HTML 구조를 알고 있습니다. 특정 파일을 "구문 분석"하고 싶습니다. 그리고 "from"과 "to"문자열이 항상 동일하다는 것을 확신합니다. – alessandronos

+0

ok 메신저로 두 번째 응답을 게시하면 모든 occourense 배열이 반환됩니다. –

+0

게시글에 올렸습니다. 페이지 하단의 –

1
/****************************************************************/ 
/* array getSelectiveContent($content,$from,$to,$exclude="") */ 
/* return array of content between provided     */ 
/* from and to positions.          */ 
/****************************************************************/ 

function getSelectiveContent($content,$from,$to,$exclude="") 
{ 
    $return = array(); // array for return elements 
    $size_FROM = strlen($from); 
    $size_TO = strlen($to); 
while(true) 
{ 
    $pos = strpos($content,$from); // find first occurance of $from 
    if($pos === false) 
    { 
     break; // if not exist break loop 
    } 
    else 
    { 
     $element = extractor($content,$from,$to); // fetch first element 
     if($exclude == "") 
     { 
      if(trim($element) != "") 
      { 
       $return[] = trim($element); 
      } 
     } 
     else 
     { 
      if(trim($element) != "" && !strstr($element,$exclude)) // if nothing in range, and exclude is not in it 
      { 
       $return[] = trim($element); // put fetched content in array. 
      } 
     } 
     $content = substr($content,$pos+strlen($element)+$size_FROM+$size_TO); // remove $from to $to from content 
    } 
} 
unset($content,$from,$to,$element,$exclude,$pos,$size_FROM,$size_TO); 
return $return; 
} 
+0

이제는 잘 작동합니다! 고맙습니다!! – alessandronos

+0

이렇게 표시해주세요. –

0
$text="this is an example of text extract in from very long long text this is my test of the php"; 
$start="this"; 
$end="of"; 
$i=substr_count($text,$start); 
$k=substr_count($text,$end); 
$len1=strlen($start); 
$len2=strlen($end); 
$temp=$text; 
for ($j=1;$j<=$i;$j++){ 
     $pos1=strpos($temp,$start); 
    $pos2=strpos($temp,$end); 
    $subs=substr($temp,$pos1+$len1,$pos2-($pos1+$len1)); 
    echo $subs.'<br/>'; 
    $temp=substr($temp,$pos2+$len2,strlen($temp)-strlen($subs)); 
} 
+0

출력물에 "인쇄"할 수있는 것처럼 보입니다. :) – alessandronos

관련 문제