如何在php中不包含html标记的情况下从字符串中选择前n个单词


how to select first n words from a string without including html tags in php

我想从存储在数据库中的文本中获取前n个单词,而不从中间剪切单词,我不想包含html标签。有什么帮助吗??例如,如果我有

<font size="2" face="georgia">   <span style="line-height: normal; text-align: justify; ">    <font color="#006600"> Indian Institute of Technology </font> - Premier Institutes for Engineering in India. </span>   </font>

我想要

印度理工学院-总理。。。

试试这个:

$it=<<<HDOC
<font size="2" face="georgia"><span style="line-height: normal; text-align: justify; "><font color="#006600"> Indian Institute of Technology </font> - Premier Institutes for Engineering in India. </span>   </font>
HDOC;
$it = trim(strip_tags($it));
// spit into words using space as delineator
$itsplit = preg_split('/ /',$it);
// get first n  words
$n = 3;
$out="";
for ($x=1; $x<=$n;$x++)
{  
  $out .=  $itsplit[$x]." ";
}
$out = substr($out,0,-1); //strip last space
echo htmlspecialchars($out); // the htmlspecialchars is to show there are no tags

您可以考虑strip_tags()来查找html标记中不包含的最后一个单词。。然后使用strpos()在带有html的字符串中找到它,并将它从开始剪切到

<?php
$string = ''; // You should specify your string here
$words = 5; // You must define how many words you need to cut from the original string here
echo(wordlimit($string));
function wordlimit($string) { 
   $length = 50;
   $ellipsis = "...";
   $words = explode(' ', strip_tags($string)); 
   if (count($words) > $length) 
       return implode(' ', array_slice($words, 0, $length)) . $ellipsis; 
   else 
       return $string; 
}
?>