函数返回子字符串和修剪字符串

时间:2011-11-16 14:14:18

标签: php function variables return substring

我想创建一个在标签之间返回内容的函数(整个字符串或开始标记后面的指定数量的字母) 线性代码如下:

$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个变量:修剪后的源和子串。所以我很想得到一个像这样的函数:

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];

1 个答案:

答案 0 :(得分: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文件)和逐行与文件,因为字符串解析可能会更好。我支持所有写作或使用现有解析器的人,因为你可能会得到更好的结果。