亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 substr 抓取前 x 個字符時如何跳過 HTML 標簽

使用 substr 抓取前 x 個字符時如何跳過 HTML 標簽

PHP
墨色風雨 2023-09-08 21:48:38
在一些博客文件中,我在 500 個字符后使用“閱讀更多”按鈕。要從字符串(即博客消息)中獲取前 500 個字符,我使用substr如下所示:$blog_message_reduced = substr($blog_message, 0, 500);該字符串$blog_message如下所示:lorem ipsum is simply dummy text of the printing and typesetting industry <img src="data/uploads/image.jpg" class="img-responsive" style="width: 100%" /> and some more text behind the image....有時,當我撰寫博客文章時,500 個字符的限制恰好位于img 標簽內。$blog_message_reducedHTML 輸出類似于:lorem ipsum is simply dummy text of the <img src="data/uplo在上面的例子中, “uploads”一詞的o已達到 500 。所以我正在尋找一種方法,img在substr使用 500 進行裁剪時忽略標簽。(img達到 500 時切勿剪切標簽;在這種情況下,請在標簽后立即剪切img)。我怎樣才能實現這個目標?
查看完整描述

1 回答

?
炎炎設計

TA貢獻1808條經驗 獲得超4個贊

在裁剪之前使用 PHP 的strip_tags()進行此操作。

<?php


$str = 'lorem ipsum is simply dummy text of the printing and typesetting industry <img src="data/uploads/image.jpg" class="img-responsive" style="width: 100%" /> and some more text behind the image.... ';

$pre = strip_tags($str);

$crop = substr($pre, 0, 100);

echo $crop;


// Output:

// lorem ipsum is simply dummy text of the printing and typesetting industry and some more text behind

或者與一些更高級的用法相同


<?php


$str = 'lorem ipsum is simply dummy text of the printing and typesetting industry <img src="data/uploads/image.jpg" class="img-responsive" style="width: 100%" /> and some more text behind the image.... ';

echo crop($str, 100, '... (read more)', true, true);


function crop($content, $maxCharacters, $append = '...', $respectWordBoundaries = false, $stripTags = false)

{

? ? if ($stripTags) {

? ? ? ? $content = strip_tags($content);

? ? }


? ? if ($maxCharacters) {

? ? ? ? if (mb_strlen($content, 'utf-8') > abs($maxCharacters)) {

? ? ? ? ? ? $truncatePosition = false;

? ? ? ? ? ? if ($maxCharacters < 0) {

? ? ? ? ? ? ? ? $content = mb_substr($content, $maxCharacters, null, 'utf-8');

? ? ? ? ? ? ? ? if ($respectWordBoundaries) {

? ? ? ? ? ? ? ? ? ? $truncatePosition = strpos($content, ' ');

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? $content = $truncatePosition ? $append . substr($content, $truncatePosition) : $append . $content;

? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? $content = mb_substr($content, 0, $maxCharacters, 'utf-8');

? ? ? ? ? ? ? ? if ($respectWordBoundaries) {

? ? ? ? ? ? ? ? ? ? $truncatePosition = strrpos($content, ' ');

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? $content = $truncatePosition ? substr($content, 0, $truncatePosition) . $append : $content . $append;

? ? ? ? ? ? }

? ? ? ? }

? ? }

? ? return $content;

}




查看完整回答
反對 回復 2023-09-08
  • 1 回答
  • 0 關注
  • 102 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號