Home > Enterprise >  Convert simple text with titles and subtiles into h2 and h3 respectively
Convert simple text with titles and subtiles into h2 and h3 respectively

Time:12-19

I am using an Open API to fetch list of titles or articles in my php/wordpress script. The format in which the API sends the response is like this :

Titles
1. The Versatile Vehicle: Driving with Style
2. Upgrade Your Ride: Discover the Thrills of Automobile Innovation
3. For Travellers and Adventurers: Exploring the Best in Automotive Design
4. Safety on the Road: Navigating with the Latest in Car Technology
5. The Lure of Luxury: Enjoying the Finest in Automotive Comfort

Subtitles
1. Expanding

So from the above response I want the Titles to be converted to h2 tags automatically and the Subtitles to h3. So it would be like this:

<h2>The Versatile Vehicle: Driving with Style</h2>

<h3>Expanding</h3>

So far I have tried this:

$ps = preg_split('#<p([^>])*>#',$txt);

This to convert p tags to array.

if (str_contains($ps[1], "Titles")) 
                    {
                        $titles = $ps[2];
                    }

This to check if string contains Titles than store that string in array after that seperated text using <br> tag.

$titles_array = preg_split('#<br([^>])*>#',$titles);

But this doesn't seem to work. I am looking for a simple php or javascript solution. Thanks in advance.

CodePudding user response:

const str = 'Titles\n'  
  '1. The Versatile Vehicle: Driving with Style\n'  
  '2. Upgrade Your Ride: Discover the Thrills of Automobile Innovation\n'  
  '3. For Travellers and Adventurers: Exploring the Best in Automotive Design\n'  
  '4. Safety on the Road: Navigating with the Latest in Car Technology\n'  
  '5. The Lure of Luxury: Enjoying the Finest in Automotive Comfort\n'  
  '\n'  
  'Subtitles\n'  
  '1. Expanding';

let arr = str.split('\n');
let flagH2 = false;
let flagH3 = false;
let strResult = '';

for (let i = 0; i < arr.length; i  ) {
  if (arr[i] === 'Titles') {
    flagH2 = true;
  }
  if (arr[i] === 'Subtitles') {
    flagH3 = true;
    flagH2 = false;
  }
  if ((arr[i] !== 'Titles') && (arr[i] !== 'Subtitles') && arr[i].length !== 0) {
    arr[i] = arr[i].substring(3);
    if (flagH2) {
      strResult  = '<h2>'   arr[i]   '</h2>\n';
    } else if (flagH3) {
      strResult  = '<h3>'   arr[i]   '</h3>\n';
    }
  }
}
console.log(strResult);

Descriptive javascript, could be compacted but if you have to change something it's fully understandable

  • Related