Search code examples
phpregexpreg-match

Using preg_match to extract a string within a string?


$data = '| years_active = 1960–70 | label = ';
preg_match('active(.*?)label', $data, $matches);
echo print_r($matches);

I was expecting this to output an array containing the value: ' = 1960–70 | ', but I just get the output: 1.

Ideally, I am trying to extract just: '1960–70'.

Where am I going wrong? Thanks.


Solution

  • Your echoing the result of print_r(), "If you would like to capture the output of print_r(), use the return parameter. When this parameter is set to TRUE, print_r() will return the information rather than print it." http://php.net/manual/en/function.print-r.php

    You also need to pre-define $matches as preg_match takes the ref to that array and you botched the regex: '/active(.*)label/'

    <?php
    $matches = array();
    $data = '| years_active = 1960–70 | label = ';
    preg_match('/active(.*)label/', $data, $matches);
    var_dump($matches);