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

Riy*_*owo 4 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>
Run Code Online (Sandbox Code Playgroud)

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

<strong> MOST </strong>
Run Code Online (Sandbox Code Playgroud)

我想删除第一个强标记,并在其中使用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>
Run Code Online (Sandbox Code Playgroud)

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

<?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;
?>
Run Code Online (Sandbox Code Playgroud)

我的代码只有结果

Most of you may have a habit of wearing socks while sleeping. <strong> Wear socks while sleeping to prevent cracking feet
Run Code Online (Sandbox Code Playgroud)

Nie*_*sol 6

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

$context = explode("</strong>",$text,2);
Run Code Online (Sandbox Code Playgroud)

但是,它会更好:

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