2013-07-26 208 views
2

我有一定的困难,这个以前也遇到过底线,所以我希望你女孩和球员,可以帮帮忙,我有几串这样匹配字符串匹配,如果

foo_bar.com     // no match 
[email protected] // match 
[email protected]_otherstuff // match 

我使用这个,但它并不完全工作,我怎么想它

[^_]+([email protected]).*

如果下划线遇到之前在我想删除@一切之后,如果没有遇到下划线,见好就收字符串独自

回答

0

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

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

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

$underscore = strpos($string, '_'); 
$at = strpos($string, '@'); 

if ($underscore !== false && $underscore < $at) { 
    $string = substr($string, 0, $at); 
} 
1

你不需要如下的代码:

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

已经接受了一个工作解决方案,但再加上一个没有环顾四周,谢谢艾伦,我不认为你可以这样做。 – ehime