简体   繁体   English

html dom中的php substr

[英]php substr in html dom

How can I use substr() in a HTML dom? 如何在HTML dom中使用substr() I want keep all the html tags and just shorten the text. 我想保留所有的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>

It could probably be a bit more robust, but this should do the trick: 它可能更健壮,但这应该可以解决问题:

$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