2012-02-28 78 views
0

我试图在某个点取一个字符串并将其切断(基本上提供了所选文本的预览),但可能存在图像或类似内容(使用BBCode为此),我想知道是否有一种简单的方法来在PHP中做到这一点。将字符串划分为一半而不切割元素

例子:

$content = "blah blah blah such and such [img]imagehere[/img] blah blah"; 
$preview=unknownfunction($content); //cuts off at approx. 40 chars 
//do not want this: 
$preview="blah blah blah such and such [img]image";//this is bad because half of image is gone 
//want this: 
$preview="blah blah blah such and such [img]imagehere[/img]"; //this is good because even though it reached 40 chars, it let it finish the image. 

有没有一种简单的方法来做到这一点?或者至少,我可以从预览元素中删除所有标签,但我仍然希望此功能不会切断任何单词。

+0

首先拆下“bbcoded”的内容,然后通过计算余下的字和分裂(MyBB的论坛,例如,工作就像是我最后一次检查) – 2012-02-28 16:38:44

+0

我觉得我经常回答这个问题。 http://stackoverflow.com/a/9202571/383402和其他答案。 – Borealid 2012-02-28 16:40:32

+0

如果您可以获取BB标签列表,您可以使用preg_match_all分割字符串,然后进行计算。否则,您可以使用'['']'字符使用正则表达式,但我不确定它如何解析无法识别的标记。 – inhan 2012-02-28 16:44:05

回答

1

继承人的功能,它使用正则表达式

<?php 
function neat_trim($str, $n, $delim='') { 
    $len = strlen($str); 
    if ($len > $n) { 
     preg_match('/(.{'.$n.'}.*?)\b/', $str, $matches); 
     return @rtrim($matches[1]) . $delim; 
    }else { 
     return $str; 
    } 
} 


$content = "blah blah blah such and such [img]imagehere[/img] blah blah"; 
echo neat_trim($content, 40); 
//blah blah blah such and such [img]imagehere[/img] 
?> 
+0

出于某种原因,这显示没有任何文字。不过,我会继续努力,看看它是否会结束工作。 – muttley91 2012-02-28 17:07:57

1

检查了这一点:

$ php -a 

php > $maxLen = 5; 
php > $x = 'blah blah blah such and such [img]imagehere[/img] blah blah'; 
php > echo substr(preg_replace("/\[\w+\].*/", "", $x), 0, $maxLen); 
blah 
1

你就会有一个问题是,你需要拿出一些规则。如果字符串是

$str = '[img]..[img] some text here... '; 

然后你会忽略图像,只是提取文本?如果是这样,你可能想要使用一些正则表达式去掉字符串副本中的所有BB代码。但随后它会考虑双方的文本中的实例,如

$str = 'txt txt [img]....[/img] txtxtxt ; // will become $copystr = 'txttxt txttxttxt'; 

你可以得到一个与第一次出现的strpos“标记”“[”,“[IMG]”,或者一个数组您不希望允许的元素。然后循环浏览这些内容,如果它们小于预期的'预览'长度,则使用该位置++作为长度。

<?php 
function str_preview($str,$len){ 
    $occ = strpos('[',$str); 
    $occ = ($occ > 40) ? 40 : $occ; 
    return substr($str,0,++$occ); 
} 
?> 

类似的东西会工作,如果你想去的第一个'['。如果你想忽略[B](或其他),并允许它们被应用,那么你会想写一个更复杂的过滤模式,允许它。或者 - 如果你想确保它在一个词的中间没有被切断,你必须考虑使用偏移的strpos('')来改变你需要它的长度。将不会有一个神奇的1班轮来处理它。

0

一个解决方案,我发现了以下

<?php 
    function getIntro($content) 
    { 
     if(strlen($content) > 350) 
     { 
      $rough_short_par = substr($content, 0, 350); //chop it off at 350 
      $last_space_pos = strrpos($rough_short_par, " "); //search from end: http://uk.php.net/manual/en/function.strrpos.php 
      $clean_short_par = substr($rough_short_par, 0, $last_space_pos); 
      $clean_sentence = $clean_short_par . "..."; 
      return $clean_sentence; 
     } 
     else 
     { 
      return $content; 
     } 
    } 
?> 

它可以防止切断的话,但它仍然可以切断标签。我可能为此做的是防止图像被张贴在预览文本中,并且显示我已经存储的预览图像。这将防止切断图像。