繁体   English   中英

将字符串分成两半而不切断任何元素

[英]Divide a String in Half Without Cutting An Element Off

我正在尝试取一个字符串并在某个点将其剪下(基本上是提供所选文本的预览),但是内部可能有图像或类似内容(为此使用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.

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

看一下这个 :

$ 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 

这是使用正则表达式的函数

<?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] 
?>

您将遇到的问题是您需要提出一些规则。 如果字符串是

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

然后,您将忽略图像而仅提取文本吗? 如果是这样,您可能想使用一些正则表达式从字符串副本中剥离所有BB代码。 但随后它将在诸如

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

您可以获得第一个出现的[[],[[img]]或您不想允许的元素数组的strpos的“标记”。 然后循环浏览,如果它们小于您所需的“预览”长度,则使用该position ++作为您的长度。

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

如果您想使用第一个'[',则类似的方法将起作用。 如果您想忽略[B](或其他)并允许应用它们,那么您将需要编写一个更复杂的过滤模式以允许使用。 或者-如果要确保它不会在单词的中间切断,则必须考虑使用offset来更改strpos(''..)的长度以达到所需的长度。 不会有神奇的1班轮来处理它。

我发现的一个解决方案是以下

<?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;
        }
    }
?>

它可以防止截断单词,但是仍然可以截断标签。 为此,我可能要做的是防止将图像发布在预览文本中,并显示已存储的预览图像。 这样可以防止裁切图像。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM