Regex to match alphanumeric characters, underscore, periods and dash, allowing dot and dash only in the middle
问题 Presently, I am using this: if (preg_match ('/^[a-zA-Z0-9_]+([a-zA-Z0-9_]*[.-]?[a-zA-Z0-9_]*)*[a-zA-Z0-9_]+$/', $product) ) { return true; } else { return false } For example, I want to match: pro.duct-name_ _pro.duct.name p.r.o.d_u_c_t.n-a-m-e But I don't want to match: pro..ductname .productname- -productname. -productname 回答1: The answer would be /^[a-zA-Z0-9_]+([-.][a-zA-Z0-9_]+)*$/ if only you allowed strings containing .- and -. NOT to match. Why would you allow them to match, anyway?