Home >Backend Development >PHP Tutorial >PHP regular matches strings that start with 'abc' and cannot end with 'xyz'
This article introduces how to use PHP regular expressions to match strings that start with "abc" and cannot end with "xyz". Friends in need can refer to it.
Requirements: Use PHP regular expressions to match strings that begin with "abc" but cannot contain "x", "y", or "z" at the end. Analysis: Starting with abc, the regular expression is written like this: ^abc. It starts with abc and must be followed by a string of characters. Generally use [^…………] to negate. Since it negates "x", "y", and "z", it is [^xyz]. The complete regular expression is this: ^abc[^xyz]*$The following is a complete php example using this regular expression, as follows: <?php $str = 'abcdef124f'; $search = '/^abc[^xyz]*$/'; if(preg_match($search,$str)) { echo $str.' 符合<br />'; }else { echo $str.' 不符合<br />'; } //output abcdef124f 符合 $str = 'abcdef12x124'; if(preg_match($search,$str)) { echo $str.' 符合<br />'; }else { echo $str.' 不符合<br />'; } //output abcdef12x124 不符合 //edit by bbs.it-home.org ?> |