How To Replace First HTML <strong></strong> Tag in PHP

php, preg-replace, preg-replace-callback, regex, replace

Solution

You can fix your code by using the optional limit argument of `explode`:

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

However, it would be better as:

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

Problem

I have a text string in 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> ``` We can see, the first strong tag is ``` <strong> MOST </strong> ``` I want to remove the first strong tag, and make word inside of it to ucwords (first letter capitalized). Result like this ``` 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> ``` I have tried with explode function, but it seem not like what I want. Here is my code ``` <?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; ?> ``` My code only result ``` Most of you may have a habit of wearing socks while sleeping. <strong> Wear socks while sleeping to prevent cracking feet ```

Original source