Php str\u ireplace和preg\u replace attemt?

Php str\u ireplace和preg\u replace attemt?,php,string,preg-replace,str-replace,Php,String,Preg Replace,Str Replace,我正在尝试替换原始文本中的字符串。(zn-->zn) 示例:“锌C3!”!锌酸锌#锌锌C9锌@锌@' 想要:锌C3!锌酸锌#锌锌C9锌@锌@' stru\u i替换尝试: $text = 'zinc zinc zinc zinc3 !zinc zincmatic #zinc zinc9 Zinc @zinc@'; $word = 'zinc'; $attr = 'zn'; // cant str_ireplace now as zincmatic will turn into znmatic

我正在尝试替换原始文本中的字符串。(
zn
-->
zn

示例:
“锌C3!”!锌酸锌#锌锌C9锌@锌@'

想要:
锌C3!锌酸锌#锌锌C9锌@锌@'

stru\u i替换尝试:

$text = 'zinc zinc zinc zinc3 !zinc zincmatic #zinc zinc9 Zinc @zinc@';
$word = 'zinc';
$attr = 'zn';

// cant str_ireplace now as zincmatic will turn into znmatic and #zinc will turn into #zn
$text = ' '.$text.' '; 
$word = ' '.$zinc.' ';

// will try now
$result = str_ireplace($word, $attr, $word);
echo trim($result);
$text = 'zinc zinc zinc zinc3 !zinc zincmatic #zinc zinc9 zinc';
$word = 'zinc';
$attr = 'zn';
$result = preg_replace("/\b($word)\b/i",$attr,$text);
echo $result;
打印<代码>锌C3!锌酸锌#锌锌C9锌@锌。仍然存在问题,如
!锌
和第二个
因空间问题而残留

预更换尝试:

$text = 'zinc zinc zinc zinc3 !zinc zincmatic #zinc zinc9 Zinc @zinc@';
$word = 'zinc';
$attr = 'zn';

// cant str_ireplace now as zincmatic will turn into znmatic and #zinc will turn into #zn
$text = ' '.$text.' '; 
$word = ' '.$zinc.' ';

// will try now
$result = str_ireplace($word, $attr, $word);
echo trim($result);
$text = 'zinc zinc zinc zinc3 !zinc zincmatic #zinc zinc9 zinc';
$word = 'zinc';
$attr = 'zn';
$result = preg_replace("/\b($word)\b/i",$attr,$text);
echo $result;
打印
zn-c3!zn zincmatic#zn zinc9 zn@zn@
几乎得到了我想要的:似乎锌会变成
zn
,即使附近有一些特殊的字符,比如
!锌
#锌
但如果有编号
zinc9
或类似
zincmatic的文本

我只想在这里放一条规则,让锌保持锌,锌保持锌和锌!锌变为
!锌

如果锌接近其中一种,是否有办法将一些例外情况添加到特殊字符中(即:

我想成为执行者的角色有
&
@


谢谢

您可以使用负数定义此类异常。它们的行为类似于
\b
,实际上可以结合使用

在本例中,您希望
(?探测前面的字符,并
(?![#&@])
测试下面的字符

= preg_replace("/(?<![#&@])\b($word)\b(?![#&@])/i",$attr,$text);
=preg_replace(“/(?)?