在我的網站上,我有一段代碼,用php的「substr」方法切斷一長串文本。但是,如果字符串中有圖像的代碼,有時會在圖像的代碼中間將其切斷,導致圖像無法正確顯示?如何讓php「substr」忽略圖片的代碼?
我該如何解決這個問題?
在我的網站上,我有一段代碼,用php的「substr」方法切斷一長串文本。但是,如果字符串中有圖像的代碼,有時會在圖像的代碼中間將其切斷,導致圖像無法正確顯示?如何讓php「substr」忽略圖片的代碼?
我該如何解決這個問題?
下面是一個功能我以前使用過:
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;
};
如何使用substr
之前呼籲文字strip_tags?如果您還需要刪除實體,也可以使用簡單的正則表達式刪除它們,或者將html_entity_decode添加到組合中。
例子:
substr(strip_tags($text), 0, 10);
我們需要看到你的代碼,能夠爲您提供任何意見都沒有。 –
@Michael他用'substr()'修剪了一段HTML字符串到一定的長度。你還需要知道什麼? – Blazemonger
@Blazemonger我們需要知道他試過的東西,代碼是如何構造的,任何可能的怪癖和/或可以做出的改進等。 – Cranio