Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/247.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在php中不包含html标记的情况下从字符串中选择前n个单词_Php - Fatal编程技术网

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

如何在php中不包含html标记的情况下从字符串中选择前n个单词,php,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 In

我想从存储在数据库中的文本中获取前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>
印度理工学院-印度一流工程学院。
我想得到


<印度技术研究所-总理…

< P>你可以考虑<代码> TrasyTAG()>代码>来查找HTML标签内没有的最后一个词。然后使用
strpos()
在html字符串中查找它,并将其从开头剪切到该位置

尝试以下操作:

$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
$it=


对我来说,它似乎包含了HTML标记…很抱歉,现在我已经更正了,现在有任何帮助吗???
n单词
。请澄清一下。单个字符作为单词类文章
a
Thanx算是很多吗?…如果我想保留html标记,最后一件事就是我该怎么做…例如。在上面的例子中,需要输出印度理工学院-Premier…这要复杂得多,因为您需要跨越标记的单词,如结束字体标记。上面的代码是基于您最初的问题,在这里,通过去掉标记直接进入文本。要做你额外要求的事情,你需要提供更多的上下文。例如,文本周围的标记在所有情况下是否始终相同?如果是,则相对容易,因为您可以将它们放回剥离文本周围,但由于您跳过了结束字体标记,因此很难将封闭标记添加回
<?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; 
}

?>