2013-02-02 31 views
4

更换的第一个HTML 标签我在PHP中的文本字符串:如何在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 

回答

6

您可以通过使用可选的限制说法explode解决您的代码:

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

然而,这将是更好的为:

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

1对于使用'preg_replace_callback'功能。但它应该是'return ucfirst(strtolower($ a [1]));'因为第一个匹配'最'是全部大写,所以你需要首先降低它,然后'ucfirst'它。此外,您需要将第四个参数传递给'preg_replace_callback' - 限制为1,因为该问题只想删除第一个'strong'标记。 – Chris

0

这将使意义:

preg_replace("<strong>(.*?)</strong>", "$1", 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可以减少服务器负载,并将样式留在应该在的位置。

UPDATE:Here's a fiddle.

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; 

Out;

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> 
0

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

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

FIDDLE DEMO