How can I use substr()
in a HTML dom? I want keep all the html tags and just shorten the text.
$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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.