preg_grep - 反转工作[关闭]

I need function working invert as preg_grep

I have array of patterns. For example

$x =['([a-z]*)\.html'=>'category','^([0-9])*-([a-zA-Z]*)'=>'article/$1'];

and string $s='176-title-of-article'

I need match string with keys of array and return replaced value from array or in this case 'article/176'.

Of course I need this for routing, but very simple and use routing modules from symfony or Zend is to heavy to my application.

Had to fix your regex to match the 176, as your existing regex only matched the first digit.

<?php

$patterns = array(
    '([a-z]*)\.html'        => 'category',
    '^([0-9]*)-([a-zA-Z]*)' => 'article/$1'
);

$in  = '176-title-of-article';
$out = null;

foreach ($patterns as $pattern => $replacement) {
    if (preg_match('/' . str_replace('/', '\\/', $pattern) . '/', $in, $match)) {
        $out = preg_replace_callback('/\$(\d+)/', function ($placeholder) use ($match) {
            if (!isset($match[$placeholder[1]])) {
                throw new Exception("route replacement contains invalid capture group '\${$placeholder[1]}'.");
            }
            return $match[$placeholder[1]];
        }, $replacement);

        break;
    }
}

var_dump($out);