Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 857
Riyanto Wibowo Avatar asked Jan 15 '23 08:01

Riyanto Wibowo


1 Answers

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);
like image 156
Niet the Dark Absol Avatar answered Jan 21 '23 23:01

Niet the Dark Absol