2012-02-28 75 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; 
     } 
    } 
?> 

它可以防止切斷的話,但它仍然可以切斷標籤。我可能爲此做的是防止圖像被張貼在預覽文本中,並且顯示我已經存儲的預覽圖像。這將防止切斷圖像。