如何让php“substr”忽略图像代码?

时间:2012-06-18 20:36:11

标签: php substr

在我的网站上,我有一个代码,可以使用php的“substr”方法切断一长串文本。但是,如果字符串中有图像代码,有时会在图像代码中间将其剪掉,导致图像无法正常显示?

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

在使用substr之前,如何在文字上调用strip_tags?如果您还需要删除实体,也可以使用简单的正则表达式删除它们,或者将html_entity_decode添加到混音中。

示例:

substr(strip_tags($text), 0, 10);

答案 1 :(得分:-2)

这是我之前使用过的一个函数:

function trimHTML($text, $max_length) {
    $tags = array();
    $result = "";

    $is_open = false;
    $grab_open = false;
    $is_close = false;
    $in_double_quotes = false;
    $in_single_quotes = false;
    $tag = "";

    $i = 0;
    $stripped = 0;

    $stripped_text = strip_tags($text);

    while ($i < strlen($text) && $stripped < strlen($stripped_text) && $stripped < $max_length) {
        $symbol = $text{$i};
        $result .= $symbol;

        switch ($symbol) {
            case '<':
                $is_open = true;
                $grab_open = true;
                break;

            case '"':
                if ($in_double_quotes)
                    $in_double_quotes = false;
                else
                    $in_double_quotes = true;

                break;

            case "'":
                if ($in_single_quotes)
                    $in_single_quotes = false;
                else
                    $in_single_quotes = true;

                break;

            case '/':
                if ($is_open && !$in_double_quotes && !$in_single_quotes) {
                    $is_close = true;
                    $is_open = false;
                    $grab_open = false;
                }

                break;

            case ' ':
                if ($is_open)
                    $grab_open = false;
                else
                    $stripped++;

                break;

            case '>':
                if ($is_open) {
                    $is_open = false;
                    $grab_open = false;
                    array_push($tags, $tag);
                    $tag = "";
                } else if ($is_close) {
                    $is_close = false;
                    array_pop($tags);
                    $tag = "";
                }

                break;

            default:
                if ($grab_open || $is_close)
                    $tag .= $symbol;

                if (!$is_open && !$is_close)
                    $stripped++;
        }

        $i++;
    }

    while ($tags) {
        $result .= "</" . array_pop($tags) . ">";
    }

    return $result;
};
相关问题