English 中文(简体)
如何在句尾或字句尾打脚
原标题:how to truncate strings at the end of a sentence or word
  • 时间:2011-02-01 14:55:44
  •  标签:
  • php

我想将部分博客员额作为员额的导言,然后在最后添加“更多”链接,但我无法找到在字句或句尾合并案文的办法。 下面的法典是空洞的 lo。

<?php

$num_of_words = 400;
while (! substr($article, $num_of_words, 1) != "")
     $num_of_words++;

?>

Any help please? Thanks

最佳回答

假设有最长的长度,即使没有白天空间,你也不想超过。

$maxlength=100; //100 characters
$mystring= I want to use part of a blog post as the introduction to the post and then add a "read more" link at the end, but I couldn t find a way to round up the text either at the end of a word or sentence. The code below runs into an empty infinite loop. ;

$mystring=substr($mystring,0,$maxlength); //now string can t be too long
$last_space=strrpos($mystring,   );
$mystring=substr($mystring,-,$last_space);

But if you really want to do it by word count, keeping in mind that words can be very long, a regex like this should match up to the 1st 25 words.

/^(w+){1,25}/
问题回答

这样做的另一个办法是:

if (strlen($article) <= 400)
    $intro = $article;
else
    $intro = substr($article, 0, strrpos($article,    , strlen($article)-400));

如果你想要获得头25个字的话,你就可以使用像你这样的东西。

^([w,:]+s+){1,25}

如果你需要更经常的表达方式,那么就要求......

<?php

$num_of_words = 400;

$art=explode(   ,$article);
$shortened=  ;
for ($i=0 ; $i<=$num_of_words ; $i++){
    $shortened.=$art[$i].   ;
}
echo $shortened;
?>

页: 1





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签