Reputation: 1200
I have a RegExp Tester extension in chrome. Running pattern [-,] against search text
"james,bayo -is a good boy" returns 2 matches
however running a preg_match as below in php returns false
<?php
preg_match("[,-]", "james,bayo -is a good boy");
?>
Expecting it to return 2 as did the regExp tester, I am sure i am missing something
Upvotes: 0
Views: 33
Reputation: 59699
You need regex delimiters, like so:
preg_match("/[,-]/", "james,bayo -is a good boy", $matches);
var_dump( $matches);
This will match one of two characters - The comma, or the dash. Also, in order to retrieve the matches, you need to specify the 3rd parameter to preg_match()
, as that it where your matches will be stored.
Note that since you're using preg_match()
, you'll only get the first match. So, as is, this will output:
array(1) {
[0]=>
string(1) ","
}
If you want all of the matches, you need to use preg_match_all()
, like this:
preg_match_all("/[,-]/", "james,bayo -is a good boy", $matches);
var_dump( $matches);
This outputs:
array(1) {
[0]=>
array(2) {
[0]=>
string(1) ","
[1]=>
string(1) "-"
}
}
Upvotes: 4