2

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
2
  • you need to use preg_replace not preg_match. Why the first numbered text was included within <h2> and the second within <h3>? Commented Mar 21, 2015 at 15:08
  • The article-title itself has <h1>, so the content will be <h2> and <h3> Commented Mar 21, 2015 at 15:31

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

For deeper level I need 'higher' heading-format. 1. should get <h2> 1.1. should get <h3>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.