skip to Main Content

I have the following text ann-ball-is-good-ok seperated by hyphen. I need to replace those hyphen and surround each text within div tags as per result sample below

<div class='cssx'>ann</div>
<div class='cssx'>ball</div>
<div class='cssx'>is</div>
<div class='cssx'>good</div>
<div class='cssx'>ok</div>

I have tried using str_replace() function but cannot get it to work

<?php
$str ="ann-ball-is-good-ok";
echo $output = str_replace('-', "<div class='cssx'></div>", $str);

?>

2

Answers


  1. You are almost there:

    $str ="ann-ball-is-good-ok";
    echo $output = "<div class='cssx'>".str_replace('-', "</div><div class='cssx'>", $str)."</div>";
    
    Login or Signup to reply.
  2.         $text = 'ann-ball-is-good-ok';
            $text = explode('-', $text);
            $result = null;
            foreach ($text as $value) {
                $result .= "<div class='cssx'>".$value."</div>";
            }
    
            echo htmlspecialchars($result);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search