How to create a regex pattern for a tag starting with a number in any order?

Viewed 34

I have a csv file as below. In this csv file the separator is & symbol.

This dataset I have consists of hundreds of rows. What I want to do is to get the 4th "li" tag. This tag always starts with a number. For example, "<li> 5..</li>" I guess this can be taken with a regex pattern. However, I could not write this pattern. I will be glad if anyone can help me.

CSV File

1412&
<h2 style="color:#000"> Info:
</h2>
<div style="text-align:center"> 
<ul> 
  <li>zxc</li> 
  <li>xv</li>
  <li>ccc</li>
  <li>5...</li>
  <li>421</li>
  <li>zxc</li> 
</ul></div>&www.example.com


1234&<h2 style="color:#000"> Info:</h2><div style="text-align:center"> <ul> <li>fsas</li> <li>aas</li><li>ccc</li><li>1 ... </li><li>ddd</li><li>eee</li> </ul></div>&www.example.com
4124&<h2 style="color:#000"> Info:</h2><div style="text-align:center"> <ul> <li>zxc</li> <li>gdsg</li><li>ccc</li><li>2... </li><li>ddd</li><li>eee</li> </ul></div>&www.example.com
1412&<h2 style="color:#000"> Info:</h2><div style="text-align:center"> <ul> <li>zxc</li> <li>xv</li><li>ccc</li><li>5... </li><li>421</li><li>zxc</li> </ul></div>&www.example.com

...
...
...

My Code

   /**
     * Read CSV file
     * 
     */
    function read_csv_file() {
        $csv_file   = fopen("data.csv", "r");  
        $csv_data   = array();
        while (($row = fgetcsv($csv_file,0,'&')) !== FALSE) { 
            $csv_data [] = $row;
        }
        return $csv_data;
    }
    $csv_data = read_csv_file();

    $descriptions = array();
    foreach ($csv_data as $key => $value) {
            //Description
            $descriptions[] = htmlentities($value[1]).'<br>';
    }
    
    //Get the fourth li tag
    $related_data = array();
    foreach ($descriptions as $description){
        
    }
1 Answers

This code reads the content of the 4th li. It should be able to handle spaces between the html tags.

foreach ($descriptions as $description){
    preg_match('/<ul>(?:\s*<li>.*?<\/li>\s*){3}<li>(.*?)<\/li>/', html_entity_decode($description), $output_array);
    $liContent = $output_array[1];
}
Related