0

How can I use the PHP function preg_match_all to match all of the following values in the HTML content in the example and get it in an array?

I need this in an array:

attribute[7]

attribute[823]

multiSelectAttribute[1663]

numericAttribute[1609]

Like this:

$shouldbe = array(attribute[7], attribute[823], multiSelectAttribute[1663], numericAttribute[1609]);

$html = '
<form>
    <input type="hidden" name="this_should_not_be_matched" value="" /> <span id=
    "syi-attribute-7" class="dropdown required" tabindex="0"><input type="hidden"
    name="attribute[7]" value="" /> <span class="label">Test...</span></span>
</form>

<ul class="item-frame">
    <li class="item" data-val="">Test...</li>

    <li class="item" data-val="30">New</li>

    <li class="item" data-val="31">Test2</li>

    <li class="item" data-val="32">Test2</li>
</ul><span id="syi-attribute-82" class="dropdown" tabindex="0"><input type="hidden"
name="attribute[823]" value="" /> <span class="label">Test...</span></span>

<ul class="item-frame">
    <li class="item" data-val="">Test...</li>

    <li class="item" data-val="393">New</li>

    <li class="item" data-val="394">New</li>

    <li class="item" data-val="395">Test2</li>
</ul>

<div class="ms-opt">
    <input id="syi-attribute-8878" type="checkbox" name="multiSelectAttribute[1663]"
    value="8878" /> <label for="syi-attribute-8878">Test2</label>
</div>

<div class="ms-opt">
    <input id="syi-attribute-8879" type="checkbox" name="multiSelectAttribute[1663]"
    value="8879" /> <label for="syi-attribute-8879">Test3</label>
</div>

<form>
    <input class="" type="text" name="numericAttribute[1609]" value="" min="0" max=
    "99" />
</form>';

I know I can use preg_match_all for it. But in my opinion it's not possible to use multiple "needles" to search through the $html haystack so I'm kinda stuck.

Community
  • 1
  • 1
Fidelity
  • 125
  • 1
  • 2
  • 8
  • 2
    http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – MrCode Jun 25 '13 at 09:54

2 Answers2

1

you can use this regex to match the elements

(multiSelect|numeric)?[Aa]ttribute\[[0-9]+\]
jcubic
  • 61,973
  • 54
  • 229
  • 402
1

Try this code. The Regular expression will match any name property with brackets on it.

//The regular expression
$regExp = "/<input[^>]*name\s*=\s*[\"'](.*?\[.*?\])['\"]/i";

// The content
$html = 'your HTML';

// The data extraction
$matchesCount = preg_match_all($regExp, $html, $matches);

// All the matches are in $matches[1]
$finalResult = $matches[1];
var_dump($finalResult);

// As you have duplicates, you can also use:
$finalResult = array_unique($finalResult );
var_dump($finalResult);
AitorF
  • 1,360
  • 1
  • 9
  • 19