将一个字符串中的所有子字符串替换为离开第一个字符串的两个字符串 - PHP
问题描述:
$regex = '([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})';
$string = 'I am emailing to [email protected] and [email protected] but [email protected]';
$newString = preg_replace($regex,'',$string);
我想用空字符串替换所有的电子邮件地址,只留下前两个。所以$ newString应该是 I am emailing to [email protected] and [email protected] but
。但徒劳无益。将一个字符串中的所有子字符串替换为离开第一个字符串的两个字符串 - PHP
我怎么办呢....
答
由于通用的答案:
使用
preg_split
与PREG_SPLIT_DELIM_CAPTURE
。在结果数组上,删除每个具有不均匀索引的数组项,从
[4]
开始。然后使用
implode()
连接其余部分。
答
你可以尝试使用爆炸
$str = I am emailing to [email protected] and [email protected] but [email protected];
$str_array = explode(, $str);
$counter = 0;
$str_out = ;
foreach($str_array as $cast){
$findme = @;
$pos = strpos($cast, $findme);
if ($pos === false) {
$str_out = $str_out . $cast . ;
}else{
$counter++;
if($counter<=2){
$str_out = $str_out . $cast . ;
}
}
}
echo $str_out;
+0
太复杂了,再加上这个删除包含@不仅仅是电子邮件地址的任何“单词”。 – zanbaldwin 2013-04-06 23:22:00
你没问几乎同样的事情就在最近? – mario 2013-04-06 22:51:15
您的正则表达式是否正确识别所有电子邮件地址? – Sepster 2013-04-06 22:52:56
使用preg_replace_callback并记录进行了多少次替换。 – 2013-04-06 23:19:45