2

如何使用正则表达式从列表中排除名称?

数据:

$subject=
"Damon Carson Stovall,
Bret Roman Mikulak,
Jack Filiberto Quirke,
Elroy Forrest Jarnagin,
Ulysses Wiley Cregger,
Brent Greg Jonah,
Bret Armand Daylong,
Ned Numbers Vandell,
Bret Alden Cutlip,
Bret Chung Markie,";

正则表达式:

// Select anyone with the first name of Bret
$pattern = "/Bret /";

我目前的解决方案:

// Loop through & Skip any line that matches Bret.
$subject_array = explode(",",$subject);

foreach($subject_array as $line)
  if(!preg_match($pattern, $line))
    echo "$line<br>";
4

2 回答 2

2

是的,您可以选择没有Bret名称的行

/^(?!Bret\b).*$/im

i是忽略大小写选项

m是一个多行选项

^描述字符串的开头

\b描绘了一个非词boundary

(?!Bret\b)是一个negative lookahead

所以只有当前瞻为真时^(?!Bret\b).*$才会选择.*一个字符串......即如果字符串不以Bret!

于 2012-12-06T19:00:56.833 回答
0

由于您的模式非常简单,因此根据preg_match() 手册页上的“注释”框,您应该使用它们strpos()或者stripos()因为它们更快:

<?

$subject = '
    Damon Carson Stovall,
    Bret Roman Mikulak,
    Jack Filiberto Quirke,
    Elroy Forrest Jarnagin,
    Ulysses Wiley Cregger,
    Brent Greg Jonah,
    Bret Armand Daylong,
    Ned Numbers Vandell,
    Bret Alden Cutlip,
    Bret Chung Markie,';

$pattern = 'Bret ';

$subject_array = explode(',', $subject);

foreach($subject_array as $line)
    if (strpos(trim($line), $pattern) !== 0)
        echo $line . '<br />';
于 2012-12-06T19:52:55.797 回答