如果匹配前遇到下划线,则匹配字符串


Match string if underscore encountered before match

我在这方面有点困难,所以我希望你们能帮忙,我有几个像这样的字符串

foo_bar.com                  // no match
foo_bar.com@some.otherstuff  // match
foo_bar.com@some_otherstuff  // match

我正在使用这个,但它不太起作用,我想要它

[^_]+(?=@).*

如果在之前和之后遇到下划线,我想删除@和之后的所有内容,如果没有遇到下划线,只需保留字符串即可。

试试这个正则表达式:

preg_replace('/((?=_).*?)@.*/', '$1', $string);

输出:

* foo_bar.com                  => foo_bar.com
* foo_bar.com@some.otherstuff  => foo_bar.com
  foobar.com@some.otherstuff   => foobar.com@some.otherstuff

您不需要查找:

$result = preg_replace('/^([^_@]*_[^@]*)@.+/', '$1', $subject);

这需要两个步骤,首先匹配,然后擦除。

if (preg_match("/_.*@/", $string))
   $string = preg_replace("/@.*$/", "", $string);

作为正则表达式的替代方案,您可以使用基本的字符串函数:

$underscore = strpos($string, '_');
$at = strpos($string, '@');
if ($underscore !== false && $underscore < $at) {
   $string = substr($string, 0, $at);
}