0

PHP配列には、以下のようなさまざまな値があります。

$values = array("news_24", "news_81", "blog_56", "member_55", "news_27");

アンダースコアの前の最初の部分 ( news, blog, member ) は動的であるため、特定のセクション ( news ) のすべての一致を取得し、その後に番号を付けたいと考えています。

以下のようなもの:

$section = "news";
$matches = preg_match('$section/[_])GETNUMBER/', $values);

これは 24 と 27 を返しますが、ニュースがアンダースコアの前にある場合のみです。

ありがとう。

4

3 に答える 3

1
$values = array("news_24", "news_81", "blog_56", "member_55", "news_27");

$section = "news"; 
foreach($values as $value) {
    $matches = preg_match("/{$section}_(\\d+)/", $value, $number);
    if ($matches)
        echo $number[1], PHP_EOL;
}
于 2013-06-22T22:04:48.890 に答える
1
$values = array("news_24", "news_81", "blog_56", "member_55", "news_27");

function func($type){
    $results = null;
    foreach($values as $val){
        $curr = explode('_',$val);
        if($curr[0]==$type){
            $results[] = $curr[1];
        }
    }
    return $results;
}

$News = func('news');

幸運を!:P

于 2013-06-22T22:06:19.333 に答える
0

Note I added two cases:

$values = array ("news_24", "news_81", "blog_56", "member_55", "news_27",
                 "blognews_99", "news_2012_12");

$section = "news";

preg_match_all("/^{$section}_(\\d+)\$/m", implode("\n", $values), $matches);

print_r($matches[1]);

The implode might not be super efficient, but it's less code. The difference is in the matching & regex.

This solution only outputs

Array
(
    [0] => 24
    [1] => 81
    [2] => 27
)

While the others also output 2012 and the solution of Mark also 99.

于 2013-06-22T22:43:41.960 に答える