Reputation: 2499
This thing really confuses me, pardon my ignorance.
I have a var $name
in here that I want to be free from number, I don't want any digit to be included in it. My preg_match()
is this:
var_dump(preg_match('/[^\d]/',$name));
Test cases:
$name = "213131"; // int(0)
$name = "asdda"; // int(1)
$name = "as232dda"; // int(1)
What I want is to have the third case to be int(0)
too.
I'm really a hard time understanding this preg_match()
, docs say it return 1 if a pattern match a subject. Here in my case, I use a negated class.
Upvotes: 0
Views: 430
Reputation: 5605
Try this:
<?php
$string = "as232dda";
$new_string = trim(str_replace(range(0,9),'',$string));
echo $new_string;// gives 'asdda'
?>
Or function form:
<?php
function remove_numbers($string){
return(trim(str_replace(range(0,9),'',$string)));
}
$string = "as232dda";
echo remove_numbers($string); // gives 'asdda'
?>
Upvotes: 0
Reputation: 6566
Your regex only checks that there is at least one non-digit. Instead, you need to check that it is only non-digits:
var_dump(preg_match('/^\D+$/',$name));
(^
and $
are the beginning and end of the string. \D
means anything not a digit--the opposite of \d
. So this only matches non-digits from beginning to end. It doesn't match an empty string. Replace +
with *
if you want to match an empty string as well).
Upvotes: 1
Reputation: 191729
#3 matches because you have both letters and numbers. Your regex in English basically says
it matches if there is a non-digit character
If you want to match only non-digit characters, you have to have the regex match against the entire string and allow for an arbitrary number of characters:
^[^\d]+$
Upvotes: 4