twan
twan

Reputation: 2659

Split string by brackets

I am trying to split a string by brackets but my array has some extra empty values.

I tried using the code of a similar question that was answered and it splits the string but also adds empty values.

//  faq data
$faq                = "SELECT * FROM `web_content` WHERE catid = 13 AND `alias` = '".$conn->real_escape_string($_GET['alias'])."' AND state = 1 ORDER BY ordering";
$faqcon             = $conn->query($faq);
$faqcr              = array();
while ($faqcr[] = $faqcon->fetch_array());

$faqtext = $faqcr[0]['introtext'];
$arr = preg_split('/\h*[][]/', $faqtext, -1, PREG_SPLIT_NO_EMPTY);

echo '<pre>';
print_r($arr);
echo '</pre>';

The output of the array is this:

Array
(
    [0] => 

    [1] => Vraag1? || Antwoord1
    [2] => 

    [3] => Vraag2? || Antwoord2
    [4] => 

    [5] => Vraag3? || Antwoord3
    [6] => 
)

My string looks like this:

<p>[Vraag1? || Antwoord1]</p>
<p>[Vraag2? || Antwoord2]</p>
<p>[Vraag3? || Antwoord3]</p>

The <p> tags are irrelevant, im not splitting on those and I can just use strip tags afterwards.

Output of answer:

 Array
    (
        [0] => Array
            (
                [0] => [Vraag1? || Antwoord1]
                [1] => [Vraag2? || Antwoord2]
                [2] => [Vraag3? || Antwoord3]
            )

        [1] => Array
            (
                [0] => Vraag1? || Antwoord1
                [1] => Vraag2? || Antwoord2
                [2] => Vraag3? || Antwoord3
            )

    )

Upvotes: 1

Views: 129

Answers (2)

Poiz
Poiz

Reputation: 7617

Did you get the result you expected (except for extra empty entries in the resulting Array)?
If your only Problem is just having empty Entries within your Array, you can quickly fix that with a combination of array_values() and array_filter() as demonstrated by the snippet below:

<?php

    $arr    = [
        '',
        'Vraag1? || Antwoord1',
        '',
        'Vraag2? || Antwoord2',
        '',
        'Vraag3? || Antwoord3',
        '',
    ];

    var_dump($arr);

    var_dump( array_values( array_filter($arr) ) );

Upvotes: 1

tarun14110
tarun14110

Reputation: 990

$line = '[This] is a [test] string, I think [this] answers [your] question.';
preg_match_all("/\[([^\]]*)\]/", $line, $matches);
var_dump($matches[1]);

Upvotes: 1

Related Questions