user3848987
user3848987

Reputation: 1657

PHP: Check if string has format of a numbered list

I want to check if a string has the format of a numbered list to format this lines correctly:

1. Something
Text
1.1. Anything
Text

Should get

<h2>1. Something</h2>
Text
<h3>1.1. Anything</h3>
Text

And so on...

I tried something like this for a preg_match:

#([\d]*\.)*\s*\K(.+?)$#s

Upvotes: 2

Views: 147

Answers (1)

anubhava
anubhava

Reputation: 785611

You can use:

$str = "1. Something\nText\n1.1. Anything\nText"; 

$result = preg_replace_callback('/^\d+\.((?:\d+\.)*)\h+.+$/m', 
          function($m) {$t=($m[1]!="")?'h3':'h2'; return "<$t>$m[0]</$t>";}, $str);

Output:

<h2>1. Something</h2>
Text
<h3>1.1. Anything</h3>
Text

RegEx Demo

Upvotes: 1

Related Questions