Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching basic HTML using regex (or any other way)

I have some HTML as follows:

    <b>This is a title: </b> 0091 + Two + 423 + Four + (Five, Six, Seven)
    <b>Some more text: </b> Abc + Hi + Random + Text + (Hello, 522, Four)
    ...
    <b>Hello world!: </b> Test + Foo + 1122 + (120, 122, Four)

Now, using php, I want to split this and make two arrays as follows:

Array 1 - (This will have everything in the <b> tags)

    [0] -> <b>This is a title: </b>
    [1] -> <b>Some more text: </b>
    ...
    [n] -> <b>Hello world!: </b>

Array 2 - (This will have everything outside the <b> tags)

    [0] -> 0091 + Two + 423 + Four + (Five, Six, Seven)
    [1] -> Abc + Hi + Random + Text + (Hello, 522, Four)
    ...
    [n] -> Test + Foo + 1122 + (120, 122, Four)

I tried to use regular expressions and preg_match_all but I just can't seem to figure them out. Any help will be highly appreciated.

Thanks!

like image 524
wiseindy Avatar asked Mar 21 '26 00:03

wiseindy


1 Answers

<?php 
$string = '    <b>This is a title: </b> 0091 + Two + 423 + Four + (Five, Six, Seven)
    <b>Some more text: </b> Abc + Hi + Random + Text + (Hello, 522, Four)
    ...
    <b>Hello world!: </b> Test + Foo + 1122 + (120, 122, Four)';
preg_match_all("#(<b>[^<]+<\/b>)([^<]+)#", $string, $matches);
print_r($matches);
?> 

Output:

Array
(
    [0] => Array
        (
            [0] => <b>This is a title: </b> 0091 + Two + 423 + Four + (Five, Six, Seven)

            [1] => <b>Some more text: </b> Abc + Hi + Random + Text + (Hello, 522, Four)
    ...

            [2] => <b>Hello world!: </b> Test + Foo + 1122 + (120, 122, Four)
        )

    [1] => Array
        (
            [0] => <b>This is a title: </b>
            [1] => <b>Some more text: </b>
            [2] => <b>Hello world!: </b>
        )

    [2] => Array
        (
            [0] =>  0091 + Two + 423 + Four + (Five, Six, Seven)

            [1] =>  Abc + Hi + Random + Text + (Hello, 522, Four)
    ...

            [2] =>  Test + Foo + 1122 + (120, 122, Four)
        )

)

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!