开发者

Search for elements that matches a pattern in PHP

I have a string like sub_category-21,cross_category-23,sub_category-33,sub_category-93,cross_category-69.

I want to obtain the numbers for sub_category and the 开发者_如何学编程ones for cross category.

What I've done since now is seperate it in an array:

$categories = explode(",", $_POST["categories"]);

$sub_categories = array();
$cross_categories = array();

foreach($categories as $category)
{

}

How I can do it?

Thank you in advance!


A regular expression is probably the most convenient solution here (you will also not need to worry about whitespace etc):

$str = 'sub_category-21,cross_category-23,sub_category-33,'.
       'sub_category-93,cross_category-69';
preg_match_all('/(sub|cross)_category-([0-9]+)/', $str, $matches,PREG_SET_ORDER);

$categories = array('sub' => array(), 'cross' => array());
foreach($matches as $match) {
    $categories[$match[1]][] = $match[2];
}

print_r($categories);

See it in action.

This code puts the results in $categories['sub'] and $categories['cross'] instead of into two separate variables as in your example for convenience. It's easy to change it if you want it done differently.

You can also do it with nested explode:

$str = 'sub_category-21,cross_category-23,sub_category-33,'.
       'sub_category-93,cross_category-69';

$categories = array();

foreach(explode(',', $str) as $category) {
    list($type, $id) = explode('-', trim($category));
    $categories[$type][] = $id;
}

print_r($categories);

See it in action.


Put the following into the foreach-loop, just as a simple idea

$category_strpos = strpos($category, "cross_category-")
    if($category_strpos == 0 && $category_strpos !== FALSE)
        $cross_categories[] = str_replace("cross_category-", "", $category);
$sub_strpos = strpos($category, "sub_category-")
    if($sub_strpos == 0 && $sub_strpos !== FALSE)
        $sub_categories[] = str_replace("sub_categories-", "", $category);


Look at split function: http://php.net/manual/en/function.split.php.

foreach($categories as $category)
{
    $split1=split("-",$category);
    $num=$split1[1];
    $name=$split1[0];
    if($name=="sub_category"){
        array_push($sub_categories,$num);
    }
    if($name=="cross_category"){
        array_push($cross_categories,$num);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜