2017-09-25 43 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

相关问题