0

My code:

$q = array('r%and_dy', 'cat09', '##$%%^');

$result = preg_grep('/[a-zA-Z0-9]+/', $q);

print_r($result);

Using the same regular expression with javascript will only match 'cat09', but in php this returns:

Array
(
    [0] => r%and_dy
    [1] => cat09
)

What do I have to write so that it only returns 'cat09'?

EDIT: you want to see the javascript. The javascript match function with the 'g' flag is the equivalent function of preg_grep in php, but it doesn't accept an array - here's a fiddle, which each item as a separate line. http://jsfiddle.net/64A5w/

EDIT: jsfiddle is down, so here is the the javascript equivalent. First I should mention, preg_grep only accepts arrays, and automatically returns global matches (it does not accept a g flag). Javascript match only accepts strings, and g must be specified.

var str = 'r%and_dy';
var result = str.match(/[a-zA-Z0-9]+/g);
document.write(result);

which displays: r,and,dy. The php equivalent would be passing preg_grep $str = array('r%and_dy'). It should return the same array But it returns r%and_dy as a single match (as shown above).

4

1 回答 1

0

Your problem is that you are matching strings that contain one or more alphanumeric character. Try:

$q = array('r%and_dy', 'cat09', '##$%%^');
$result = preg_grep('/^[a-zA-Z0-9]+$/', $q);    
print_r($result);

The ^ and $ mean the start and the end of the string respectively.

From the manual:

Returns the array consisting of the elements of the input array that match the given pattern.

于 2013-03-30T19:56:26.200 回答