2011-11-16 65 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文件),并且逐行扫描与文件扫描可能会更好地工作。我支持所有写过或使用现有解析器的人,因为您可能会获得更好的结果。