Search code examples
phpstring-matching

Get specific content from a string


I need to get numbers as an array from a given string.

Example string:

$t = '1-P,2-T,3-P,4-R,5-C,6-T,';

Expected output:

  • if I search -T the output needs to be like this:
array(
    [0] => 2,
    [1] => 6
)
  • if it's -P:
array(
    [0] => 1,
    [1] => 3
)

I tried var_export(explode("-T,",$t)); but it didn't work as expected. Can any one give me a suggestion to get this?


Solution

  • The below matches the full integer number which preceeds the search term -P.
    Let's keep it concise:

    $matches = array();
    if (preg_match_all('/([0-9]+)\-P/', $t, $matches) >= 1) {
        var_dump($matches[1]);
    }
    

    Search for '/([0-9]+)\-P/, '/([0-9]+)\-C/, '/([0-9]+)\-T/ an so on.


    A more dynamic way to look for different search terms/filters:

    $filter = '-T';
    $pattern = sprintf('/([0-9]+)%s/', preg_quote($filter));
    

    See preg_match_all and preg_quote functions.