2017-09-25 139 views
0

我從php.net得到了這個函數,用於在大寫的情況下將大寫字母轉換爲小寫字母。在製作每個句子大寫的第一個字母的段落中?

function sentence_case($string) { 
    $sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE); 
    $new_string = ''; 
    foreach ($sentences as $key => $sentence) { 
     $new_string .= ($key & 1) == 0? 
      ucfirst(strtolower(trim($sentence))) : 
      $sentence.' '; 
    } 
    return trim($new_string); 
} 

如果句子不在段落中,一切正常。但如果句子在段落中,開頭段落(<p>)或中斷(<br>)標記HTML中的第一個字母變爲小寫。

這是樣板:

前:

<p>Lorem IPSUM is simply dummy text. LOREM ipsum is simply dummy text! wHAt is LOREM IPSUM? Hello lorem ipSUM!</p> 

輸出:

<p>lorem ipsum is simply dummy text. Lorem ipsum is simply dummy text! What is lorem ipsum? Hello lorem ipsum!</p> 

有人可以幫助我,使在該段成爲大寫字母的第一個字母?

感謝

回答

0

你的問題是,你正在考慮在判決書送達之HTML ,所以句子的第一個「單詞」是<P>lorem,而不是Lorem

您可以更改正則表達式來讀取/([>.?!]+)/,但這樣一來,你會看到多餘的空格「排版」之前的系統現在看到句子,而不是一個。

另外,現在Hello <em>there</em>將被視爲四個句子。

這看起來令人不安,就像「我如何使用正則表達式來解釋(X)HTML」一樣?

0

你可以用CSS做很容易

p::first-letter { 
    text-transform: uppercase; 
} 
+0

我知道我可以使用 'P:第一字母',但我不想要,笨蛋搜索引擎(谷歌機器人)仍搶小寫。我認爲這對SEO不好。謝謝。 – v123shine

+0

據我所知,搜索引擎優化不關心大寫或小寫。它只關注它內的內容 – codegeek

-1

在HTML

p.case { 
 
    text-transform: capitalize; 
 
}
<p class="case">This is some text and usre.</p>

0

試試這個

function html_ucfirst($s) { 
return preg_replace_callback('#^((<(.+?)>)*)(.*?)$#', function ($c) { 
     return $c[1].ucfirst(array_pop($c)); 
}, $s); 
} 

,並調用這個函數

$string= "<p>Lorem IPSUM is simply dummy text. LOREM ipsum is simply dummy text! wHAt is LOREM IPSUM? Hello lorem ipSUM!</p>"; 
echo html_ucfirst($string); 

這裏工作演示:https://ideone.com/fNq3Vo

相關問題