2011-11-16 66 views
1

我想提出一個返回標籤之間的內容(無論是整個字符串或者開始標籤後的指定數量的字母) 線性代碼如下功能:函數返回子和修剪串

$tag='<body>'; 
//case1 
$source=substr($source,strpos($source,$tag)+strlen($tag)); 
$sub=substr($source,0,strpos($source,'<')); 
//case2 
$source=substr($source,strpos($source,$tag)+strlen($tag)); 
$sub=substr($source,0,3); 

該函數將接受3個參數:源代碼,指定的標記和子字符串長度(對於情況2)並將返回2個變量:修剪後的源和子字符串。所以basicaly我想有這樣的功能:

function p($source,$tag,$len) { 
    $source=substr($source,strpos($source,$tag)+strlen($tag)); 
    if(isset($len)) $sub=substr($source,0,$len); 
    else $sub=substr($source,0,strpos($source,'<')); 
    $ret=array(); 
    $ret[0]=$source; 
    $ret[1]=$sub; 
    return $ret; 
} 
// 
$source=p($source,'<strong>')[0]; 
$sub1=p($source,'<strong>')[1]; 
$source=p($source,'<p>',100)[0]; 
$sub2=p($source,'<p>',100)[1]; 
+0

這是什麼語言?請用該語言重新標記。 –

+0

也許使用XML解析器? http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html –

+0

@FrostyZ我不需要解析所有的代碼,只需選擇標籤和1個函數就足夠了。 – user965748

回答

0
function get_inner_html($source, $tag, $length = NULL) 
{ 
    $closing_tag = str_replace('<', '</', $tag); // HTML closing tags are opening tags with a preceding slash 
    $closing_tag_length = strlen($closing_tag); 
    $tag_length = strlen($tag); // Will need this for offsets 
    $search_offset = 0; // Start at the start 
    $tag_internals = FALSE; 
    while (strpos($source, $tag, $search_offset)) // Keep searching for tags until we find no more 
    { 
     $tag_position = strpos($source, $tag, $search_offset); // Next occurrence position 
     $tag_end = strpos($source, $closing_tag, $search_offset); // Next closing occurrence 
     if ($length == NULL) 
     { 
      $substring_length = $tag_end - ($tag_position + $tag_length); 
     } else 
     { 
      $substring_length = $length; 
     } 
     $substring = substr($source, $tag_position + $tag_length, $substring_lenth); 
     $tag_internals[] = $substring; 
     $search_offset = $tag_end + $closing_tag_length; // The next iteration of loop will start at this position, effectively trimming off previous locations 
    } 
    return $tag_internals; // Returns an array of findings for this tag or false if tag not found 
} 

你的問題說,滿弦或根據傳遞長度的子集。如果您需要這兩個選項,則需要刪除if並執行第二個substr以拉出完整的字符串。可能將其保存到另一個數組並返回兩個數組的數組,其中一個是完整的字符串,另一個是修剪過的字符串。

我沒有運行此代碼,因此可能存在一些錯誤(閱讀:確實存在),它只適用於最基本的標記。如果您的任何標籤都有屬性,您需要修改這些屬性並調整結束標籤計算,以防止長時間關閉不存在的標籤。

這是一個簡單的例子,但請記住,很多PHP字符串函數都有點貪心,不適合處理長字符串(如完整的HTML文件),並且逐行掃描與文件掃描可能會更好地工作。我支持所有寫過或使用現有解析器的人,因爲您可能會獲得更好的結果。