2

I am pretty green when it comes to php, so here's a basic question for which I have not found an answer yet.

I extract repetitive information from a page by doing regex matching as follows. The regex has two capturing groups (...), hence the $matches array has index ranging from 0 (full regex value) to 2 ( 1 and 2 are the capturing group values).

<?php
    $page = file_get_contents(url);
    preg_match_all(regex-with-two-capturing-groups, $page, $matches);
    $m1 = $matches[1];
    $m2 = $matches[2];
    for ($i=0; $i < sizeof($m1); $i++) {
        echo ("<tr><td>$m1[$i]</td><td>$m2[$i]</td></tr>");
    }
?>

This works fine, but at first I tried a shorter version:

<?php
    $page = file_get_contents(url);
    preg_match_all(regex-with-two-capturing-groups, $page, $matches);
    for ($i=0; $i < sizeof($matches[0]); $i++) {
        echo ("<tr><td>$matches[1][$i]</td><td>$matches[2][$i]</td></tr>");
    }
?>

but this resulted in

<tr><td>Array[0]</td><td>Array[0]</td></tr>
<tr><td>Array[1]</td><td>Array[1]</td></tr>
<tr><td>Array[2]</td><td>Array[2]</td></tr>
<tr><td>Array[3]</td><td>Array[3]</td></tr>
<tr><td>Array[4]</td><td>Array[4]</td></tr>
...

Why is this?
And is there a way to do two-dimensional indexing in one expression, not having to define intermediate arrays m1 and m2?

1 Answer 1

2

Use this code:

<?php
    $page = file_get_contents(url);
    preg_match_all(regex-with-two-capturing-groups, $page, $matches);
    for ($i=0; $i < sizeof($matches[0]); $i++) {
        echo ("<tr><td>".$matches[1][$i]."</td><td>".$matches[2][$i]."</td></tr>");
    }
?>

PHP Documentation : language.types.string.parsing

Look also here : PHP: concatenation of multidimensional array elements

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

2 Comments

All right, so . (dot) is sort of a string concatenate operator?
@Maestro13 : Maybe because of multi-dimensional array qualifier.Always use . as concatenation, it increase readability of your code and prevents you from solving such issues.See my updated answer.

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.