$value = "[email protected]@[email protected]";
删除字符串的preg_replace重复字符
$clear = preg_replace('/@{1,}/', "", $value);
我需要删除重复的@和得到的东西,如:
[email protected]
(我只需要先@)
怎么办那?
$value = "[email protected]@[email protected]";
删除字符串的preg_replace重复字符
$clear = preg_replace('/@{1,}/', "", $value);
我需要删除重复的@和得到的东西,如:
[email protected]
(我只需要先@)
怎么办那?
一个正则表达式的方法:
$clear = preg_replace('~(?>@|\G(?<!^)[^@]*)\[email protected]*~', '', $value);
细节:
(?: # open a non capturing group
@ # literal @
| # OR
\G(?<!^) # contiguous to a precedent match, not at the start of the string
[^@]* # all characters except @, zero or more times
)\K # close the group and reset the match from the result
@* # zero or more literal @
这不是一个原子组吗?无论如何+1000 :) – HamZa
@HamZa:是的,它可以被替换成'(?:...)',因为它在内部交替是无用的。 –
作品!谢谢!! – Aleksandar
这给一试:
// The original string
$str = '[email protected]@CCm[email protected]';
// Position of the first @ sign
$pos = strpos($str, '@');
// Left side of the first found @ sign
$str_sub_1 = substr($str, 0, $pos + 1);
// Right side of the first found @ sign
$str_sub_2 = substr($str, $pos);
// Replace all @ signs in the right side
$str_sub_2_repl = str_replace('@', '', $str_sub_2);
// Join the left and right sides again
$str_new = $str_sub_1 . $str_sub_2_repl;
echo $str_new;
首先,告诉我们您已经尝试 –
'strpos' +'substr_replace',不需要使用正则表达式(特别是如果你不能写一个 - 对你来说维护会很痛苦n此代码) – zerkms
@zerkms:它可以是一个好方法,你只能跳过第一个。 –