将这些结果拆分为数组

时间:2011-10-26 01:06:50

标签: php regex

我真的很难让一些正则表达式转向:

Child Non Peak @ $10.75 USD <br/>
<input name="quan0" maxlength="1" size="1" class="star_N"/> <br>
Infant Non Peak @ $13.75 USD <br/>
<input name="quan1" maxlength="1" size="1" class="star_N"/> <br>
Adult Non Peak @ $13.75 USD <br/>
<input name="quan2" maxlength="1" size="1" class="star_N"/> <br>
Senior Non Peak @ $12.50 USD <br/>
<input name="quan3" maxlength="1" size="1" class="star_N"/> <br>
Member Adult Non Peak @ $12.75 USD <br/>
<input name="quan4" maxlength="1" size="1" class="star_N"/> <br>
Member Senior Non Peak @ $11.50 USD <br/>
<input name="quan5" maxlength="1" size="1" class="star_N"/> <br>
Member Child Non Peak @ $9.75 USD <br/>
<input name="quan6" maxlength="1" size="1" class="star_N"/> <br>

进入类似

的数组
array (
 value: Child Non Peak @ $10.75 USD 
 price: 10.75

有人可以帮忙吗?我已经拥有了这个很复杂的正则表达式,但它不适合用途。

preg_match_all('/class="t12">(?P<type>\w+)[\s@]*(?P<cost>\$[\d.]*)\s+USD(.*)name="(?P<input>quan\w+)"/msU',
               $output,
               $matches,
               PREG_SET_ORDER);

3 个答案:

答案 0 :(得分:1)

([a-zA-Z ]+ @ \$(\d+\.\d{2}) USD)应该可以给你带来好成绩

  • [a-zA-Z ]+是产品名称,
  • @介于产品和价格之间
  • \$(\d+\.\d{2})价格,group捕获至少1位数后跟a。后跟2位数字
  • USD捕获最后一个空格和货币参考

答案 1 :(得分:1)

preg_match_all('/[\w ]* @ \$?([0-9]{1,}\.?[0-9]*) [A-Z]{2,3} ?/', $output, $matches, PREG_SET_ORDER);

print_r( $matches );

给出了下一个结果:

Array
(
    [0] => Array
        (
            [0] => Child Non Peak @ $10.75 USD 
            [1] => 10.75
        )
    [1] => Array
        (
            [0] => Infant Non Peak @ $13.75 USD 
            [1] => 13.75
        )
    [2] => Array
        (
            [0] => Adult Non Peak @ $13.75 USD 
            [1] => 13.75
        )
    [3] => Array
        (
            [0] => Senior Non Peak @ $12.50 USD 
            [1] => 12.50
        )
    [4] => Array
        (
            [0] => Member Adult Non Peak @ $12.75 USD 
            [1] => 12.75
        )
    [5] => Array
        (
            [0] => Member Senior Non Peak @ $11.50 USD 
            [1] => 11.50
        )
   [6] => Array
        (
            [0] => Member Child Non Peak @ $9.75 USD 
            [1] => 9.75
        )
)

答案 2 :(得分:0)

使用像DOMDocument这样的DOM解析器来检查元素。

使用正则表达式解析HTML可能会导致unintended consequences