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

最佳答案

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

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

但是,它会更好:
$context = preg_replace_callback("(<strong>(.*?)</strong>)",function($a) {return ucfirst($a[1]);},$text);

关于php - 如何在 PHP 中替换第一个 HTML <strong></strong> 标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14658732/

10-10 08:03