4

我在 PHP 中有一个文本字符串:

<strong> MOST </strong> of you may have a habit of wearing socks while sleeping. 
<strong> Wear socks while sleeping to prevent cracking feet</strong>
<strong> Socks helps to relieve sweaty feet</strong>

我们可以看到,第一个强标签是

<strong> MOST </strong>

我想删除第一个强标签,并将其中的单词变成 ucwords(首字母大写)。像这样的结果

Most of you may have a habit of wearing socks while sleeping. 
<strong> Wear socks while sleeping to prevent cracking feet</strong>
<strong> Socks helps to relieve sweaty feet</strong>

我尝试过使用爆炸功能,但它似乎不是我想要的。这是我的代码

<?php
$text = "<strong>MOST</strong> of you may have a habit of wearing socks while sleeping. <strong> Wear socks while sleeping to prevent cracking feet</strong>. <strong> Socks helps to relieve sweaty feet</strong>";
$context = explode('</strong>',$text);
$context = ucwords(str_replace('<strong>','',strtolower($context[0]))).$context[1];
echo $context;
?>

我的代码只有结果

Most of you may have a habit of wearing socks while sleeping. <strong> Wear socks while sleeping to prevent cracking feet
4

5 回答 5

6

您可以使用以下的可选限制参数来修复您的代码explode

$context = explode("</strong>",$text,2);

但是,最好是:

$context = preg_replace_callback("(<strong>(.*?)</strong>)",function($a) {return ucfirst($a[1]);},$text);
于 2013-02-02T04:56:27.713 回答
3

我知道您要求使用 PHP 解决方案,但我不认为向您展示 CSS 解决方案会受到伤害:

HTML

<p><strong>Most</strong> of you may have a habit of wearing socks while sleeping.</p>

CSS

p strong:first-child {
    font-weight: normal;
    text-transform: uppercase;
}

除非有使用 PHP 的特定原因,否则我认为它只是使本来应该很容易的事情变得复杂。使用 CSS 可以减少服务器负载并将样式留在应有的位置。

更新: 这是一个小提琴。

于 2013-02-02T04:58:17.347 回答
0

这是有道理的:

preg_replace("<strong>(.*?)</strong>", "$1", 1)
于 2013-02-02T04:57:25.577 回答
0

这提供了preg_replace_callback

$s = '<strong> MOST </strong> of you may have a habit of wearing socks while sleeping.
      <strong> Wear socks while sleeping to prevent cracking feet</strong>
      <strong> Socks helps to relieve sweaty feet</strong>';
$s = preg_replace_callback('~<strong>(.*?)</strong>~i', function($m){
    return ucfirst(strtolower(trim($m[1])));
}, $s, 1);
print $s;

出去;

Most of you may have a habit of wearing socks while sleeping.
<strong> Wear socks while sleeping to prevent cracking feet</strong>
<strong> Socks helps to relieve sweaty feet</strong>
于 2013-02-02T05:13:17.620 回答
0

我必须同意@thordarson,他的回答不会改变你的内容,这对我来说更好。因为您的问题基本上是布局问题。这是我根据他的回答改编的版本。不同之处在于您首先将强文本重新恢复为正常格式。然后你把第一个字母大写。

   strong {
        font-weight: normal;
    }
    strong:first-letter {
        font-weight: normal;
        text-transform: uppercase;
    }

小提琴演示

于 2013-02-04T09:04:23.957 回答