簡體   English   中英

html dom中的php substr

[英]php substr in html dom

如何在HTML dom中使用substr() 我想保留所有的html標簽,只是縮短文本。

$str = '<div><a href="http://www.weather.com">Today is a nice day</a></div>';
$part1 = preg_replace("/<a(.*?)>(.*?)<\/a>/i",substr('\\2', 0,10),$str).'...';
$part2 = preg_replace("/<a(.*?)>(.*?)<\/a>/i",'\\2',$str);
echo str_replace($part2,$part1,$str);// nothing change
// I need <div><a href="http://www.weather.com">Today is a...</a></div>

它可能更健壯,但這應該可以解決問題:

$str = '<div><a href="http://www.weather.com">Today is a nice day</a></div>';
echo shortenLinks($str);

function shorten($matches) {
   $maxlen = 10;
   $str = $matches[2];
   if (strlen($str) > $maxlen) {
      return "<" . $matches[1] . ">" . substr($str, 0, $maxlen) . "...<";
   } else {
      return $matches[0];
   }
}

function shortenLinks($str) {
   $pattern = "/<(a\s+.*)>([^<]+)</";
   return preg_replace_callback($pattern, "shorten", $str);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM