开发者

Search an Array and remove entry if it doesn't contain A-Z or a A-Z with a dash

I have the following Array:

Array
(
    [0] => text
    [1] => texture
    [2] => beans
    [3] => 
)开发者_如何学编程

I am wanting to get rid of entries that don't contain a-z or a-z with a dash. In this case array item 3 (contains just a space).

How would I do this?


Try with:

$input = array( /* your data */ );

function azFilter($var){
    return preg_match('/^[a-z-]+$/i', $var);
}
$output = array_filter($input, 'azFilter');

Also in PHP 5.3 there is possible to simplify it:

$input = array( /* your data */ );

$output = array_filter($input, function($var){
    return preg_match('/^[a-z-]+$/i', $var);
});


Try:

<?php
    $arr = array(
        'abc',
        'testing-string',
        'testing another',
        'sdas 213',
        '2323'
    );

    $tmpArr = array();
    foreach($arr as $str){
        if(preg_match("/^([-a-z])+$/i", $str)){
            $tmpArr[] = $str;
        }
    }
    $arr = $tmpArr;
?>

Output:

array
  0 => string 'abc' (length=3)
  1 => string 'testing-string' (length=14)


For the data you have provided in your question, use the array_filter() function with an empty callback parameter. This will filter out all empty elements.

$array = array( ... );
$array = array_filter($array);

If you need to filter the elements you described in your question text, then you need to add a callback function that will return true (valid) or false (invalid) depending on what you need. You might find the ctype_alpha functions useful for that.

$array = array( ... );
$array = array_filter($array, 'ctype_alpha');

If you need to allow dashes as well, you need to provide an own function as callback:

$array = array( ... );
$array = array_filter($array, function($test) {return preg_match('(^[a-zA-Z-]+$)', $test);});

This sample callback function is making use of the preg_match() function using a regular expression. Regular expressions can be formulated to represent a specifc group of characters, like here a-z, A-Z and the dash - (minus sign) in the example.


Ok , simply you can loop trough the array. Create an regular expression to test if it matches your criteria.If it fails use unset() to remove the selected element.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜