简体   繁体   中英

Regex in PHP to match words with some excepetions

$matchstring  = 'MS-DOS file';
$string1 = 'MS-DOS file';
$string2 = 'MS-DOS file, NE Windows';
$string3 = 'MS-DOS file, MZ OS-windows';
$string4 = 'MS-DOS file, Clear OS-windows';

I am writing the regex to march the string 'MS-DOS file' in above strings to only match $string1 and $string4 . The pattern should not match the 'MS-DOS file' which is followed by the keywords 'NE' or 'MZ'. For other it should match like it should match string 4 but not string 2,3

Any ideas ?

I was tried this with my poor regex but no luck :(

if (preg_match("/MS-DOS file[\s]?[^MZ][^NE]/", $string1)){
    echo "True";
} else{
    echo "False";
}

Try this:

"/MS-DOS file(?:,\s|$)(?!MZ|NE).*/"

You were overlooking the comma and misusing the character set square brackets.

EDIT: Also, I believe you want to check for 'NE', not 'NI'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM