2011-11-03 27 views
1

我有一些HTML鏈接的文本,就像切一的「鏈接」,如果它的長度超過30個字符

<a href="urlThatIneedToCutBecauseItIsTooLongAndWithoutEmptySpaceItDoestGetANewLineWhenItIsPrintedByTheBrowser">urlThatIneedToCutBecauseItIsTooLongAndWithoutEmptySpaceItDoestGetANewLineWhenItIsPrintedByTheBrowser</a> 

,我需要剪切的文本(而不是鏈接),如果是長於一些字符(比方說30)。所以鏈接必須變得如下:

<a href="urlThatIneedToCutBecauseItIsTooLongAndWithoutEmptySpaceItDoestGetANewLineWhenItIsPrintedByTheBrowser">urlThatIne... ...TheBrowser</a> 

我該怎麼辦?正則表達式?我使用PHP和jQuery(但我想做它服務器端)。

回答

7

可能有一個正則表達式的方法,但我會選擇一個簡單的substr()

if (strlen($title)>30) { 
    $title=substr($title, 0, 10) . "..." . substr($title, -10); 
} 
+0

你說得對!在這種簡單的情況下,不需要正則表達式。 – ComFreek

+0

不!這樣做它也計算'a','href'鏈接和文本....不僅文本... – markzzz

+0

@markzzz,你說你想剪文本...我已經假定你已經解析DOM。如果你還沒有這樣做,你需要一個DOM解析器來獲取該標籤的內部文本。 yasar11732建議一個。 – Brad

1

如果你想鏈接的文字,以表明它已被截斷......

function printLink($url){ 
    $text = strlen($url) > 30 
      ? substr($url, 30) . '&hellip;' 
      : $url; 

    echo '<a href="' . $url . '">' . $text . '</a>'; 
} 

printLink('urlThatIneedToCutBecauseItIsTooLongAndWithoutEmptySpaceItDoestGetANewLineWhenItIsPrintedByTheBrowser'); 
// <a href="urlThatIneedToCutBecauseItIsTooLongAndWithoutEmptySpaceItDoestGetANewLineWhenItIsPrintedByTheBrowser">urlThatIneedToCutBecauseItIsT…</a> 
+0

就像對布拉德說的那樣,這也算是a,href鏈接和文本....不僅文字... – markzzz

2

只需使用CSS。

<a href="urlThatIneedToCutBecauseItIsTooLongAndWithoutEmptySpaceItDoestGetANewLineWhenItIsPrintedByTheBrowser">urlThatIne... ...TheBrowser</a> 

a { 
    white-space: nowrap; 
    overflow: hidden; 
    text-overflow: ellipsis; 
    width: 300px; 
    -o-text-overflow: ellipsis; 
    -ms-text-overflow: ellipsis; 
} 
+0

它不是跨瀏覽器... – markzzz

+0

@markzzz,但它回落很好! – Brad

+0

[也需要'display:block'](http://stackoverflow.com/questions/12820007/text-overflowellipsis-on-a-link/12820195#12820195) – laggingreflex

相關問題