簡體   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