Home » Php » php – Regular expression – repeat groups

php – Regular expression – repeat groups

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have text:

<b>Title1:</b><br/><b>Title2:</b> Value1<br/><b>Title3:</b> Value2<br/><b>Title4:</b> Value3<br/>Value4<b>Title5:</b> Value5<br/>

What regex to get:

[0] => <b>Title1:</b><br/>
[1] => <b>Title2:</b> Value1<br/>
[2] => <b>Title3:</b> Value2<br/>
[3] => <b>Title4:</b> Value3<br/>Value4
[4] => <b>Title5:</b> Value5<br/>

My variant not working:
<b>(.*?)</b>(.*?)

How to&Answers:

You can use preg_split() with a lookahead:

<?php
$split = preg_split( '/(?=<b>Title\d+:)/', '<b>Title1:</b><br/><b>Title2:</b> Value1<br/><b>Title3:</b> Value2<br/><b>Title4:</b> Value3<br/>Value4<b>Title5:</b> Value5<br/>' );
array_shift( $split );
var_dump( $split );

Output:

array(5) {
  [0]=>
  string(19) "<b>Title1:</b><br/>"
  [1]=>
  string(26) "<b>Title2:</b> Value1<br/>"
  [2]=>
  string(26) "<b>Title3:</b> Value2<br/>"
  [3]=>
  string(32) "<b>Title4:</b> Value3<br/>Value4"
  [4]=>
  string(26) "<b>Title5:</b> Value5<br/>"
}

Your regex was close, you need:

<b>(.*?)<\/b>(.*?)(?=<b>|$)

https://regex101.com/r/dk67IK/1

Answer:

A resource like this can be very useful in troubleshooting regex: https://regex101.com/

Looks like you are missing an escape character in <b>(.*?)</b>(.*?)

<b>(.*?)<\/b>(.*?) should stop an error from being thrown for that current regex and get you close to the result, you’ll need to work with it a bit more to get the exact results you want though.

<b>(.*?)<\/b>(.*?)<br\/> should be a bit closer I think as it looks like you want to include the break tags.