如何在PHP中替换第一个HTML <strong> </strong>标记

时间:2013-02-02 04:51:25

标签: php regex replace preg-replace preg-replace-callback

我在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

5 个答案:

答案 0 :(得分:6)

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

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

然而,它会更好:

$context = preg_replace_callback("(<strong>(.*?)</strong>)",function($a) {return ucfirst($a[1]);},$text);

答案 1 :(得分: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可以减少服务器负载并使样式保持原样。

更新: Here's a fiddle.

答案 2 :(得分:0)

这是有道理的:

preg_replace("<strong>(.*?)</strong>", "$1", 1)

答案 3 :(得分: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>

答案 4 :(得分:0)

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

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

FIDDLE DEMO