PHP regex: combine preg_match and preg_replace
$pattern = "/^[a-zA-Z0-9]{1,30}$/";
$string = preg_replace("Description", "", $description);
if(preg_match($pattern, $string)){
//do some stuff
}
How would I adjust the regex pattern to fail when "Descript开发者_如何转开发ion" is found in the string.
You use something called negative lookahead -- a zero-width assertion. This means that it checks something in the string without actually "eating" any of it, so things that follow the assertion start where the assertion started. Negative lookahead means that if it finds the string, the regex fails to match. You do this with (?!...)
where "..." is a placeholder for you want to avoid. So in your case, where you want to avoid Description:
$pattern = "/^(?!.*Description)[a-zA-Z0-9]{1,30}$/";
In (?!.*Description)
, the .*
at the beginning is there to make sure Description doesn't appear anywhere at all in the string (i.e. Any number of any characters can come before Description and it will still fail if Description is in there somewhere). And remember, this is zero-width, so after it does the check for not Description, it starts back again where it was, in this case the very beginning of the string.
Don't use a regex for that.
if( strpos($string,"Description") === false) {
// "Description" is NOT in the string
}
精彩评论