Azamat Azamat - 1 month ago 8
PHP Question

PHP: Convert line break into list item and wrap part of string with span

I'm converting HTML template into WordPress theme. On backend I have a custom field that outputs raw text.

This is what I want to achieve in the end:

list items

This is the HTML output I want to achieve:



<li>Bor ekan <span class="disk-year">/ 2002</span></li>
<li>Baxt bo'ladi <span class="disk-year">/ 2004</span></li>
<li>Baxtliman <span class="disk-year">/ 2005</span></li>
<li>Bu mening tanlovim <span class="disk-year">/ 2005</span></li>
<li>Radio tinglamayman <span class="disk-year">/ 2005</span></li>
<li>Yana albomlar <span class="disk-year">/ 2005</span></li>
<li>Yana bitta uzun <span class="disk-year">/ 2005</span></li>
<li>Yangi yil albomi <span class="disk-year">/ 2005</span></li>
<li>Eng yaxshi <span class="disk-year">/ 2005</span></li>
<li>Ba'zi qo'shiqlar <span class="disk-year">/ 2005</span></li>
<li>Ko'p yuklab olingan <span class="disk-year">/ 2005</span></li>
<li>Yevropa hitlari <span class="disk-year">/ 2005</span></li>





I want user to enter strings separated with line breaks like these:


Music album name * / 2007*
Music album name * / 2007*
Music album name * / 2007*
Music album name * / 2007*
Music album name * / 2007*



  1. Each string on new line should be wrapped with li tags;

  2. Everything between *'s should be wrapped with span tags.


Answer

Could You have meant something like below? Quick-Test Here.

<?php

    $data   = "Bor ekan * / 2002*\nBaxt bo'ladi * / 2004*\nBaxtliman * / 2005*\nBu mening tanlovim * / 2005*\nRadio tinglamayman * / 2005*\nYana albomlar * / 2005*\nYana bitta uzun * / 2005*\nYangi yil albomi * / 2005*\nEng yaxshi * / 2005*\nBa'zi  qo'shiqlar * / 2005*\nKo'p yuklab olingan * / 2005*\nYevropa hitlari * / 2005*\n";

    function transformData($data){
        $output         = '';
        if(is_string($data)){
            $data       = explode('\n', $data);
        }

        foreach($data as $val){
            $extract    = preg_replace("#(.*?)\*(.*?)\*#", "<li>$1<span class='disk-year'>$2</span></li>", $val);
            $output    .= $extract . PHP_EOL;
        }

        return $output;
    }

    var_dump(transformData($data));