str_ireplace 和 preg_replace 尝试?
我正在尝试替换原始文本中的字符串。 ( zinc
--> zn
)
示例:'zincZnzincZn3!zinczincmatic#zinczinc9Zinc@zinc@'
想要:< code>'zn zn znZn3!znZnmatic#zincZn9zn@zinc@'
str_ireplace 尝试:
$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);
打印znZnznZn3 !锌zincmatic #zincZn9zn@zinc@
。 和第二个 zinc
由于空间问题而仍然存在。
仍然存在问题,
$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;
因为 ! zinc znZnmatic#znZn9zn@zn@
几乎得到了我想要的:似乎锌会变成 zn
即使附近有一些特殊的字符,如 !zinc
或 #zinc
但不是如果有数字 zinc9
或类似 zincmatic
的文本,
我只想在此处放置一条规则,以便 #zinc
保留 #zinc< /代码>,<代码>@zinc@保持
@zinc@
和 !zinc
变成 !zn
如果锌靠近其中一个,有没有办法向特殊字符添加一些例外(即:#zinc
、zinc#
、zinc@
、@zinc
)
我想成为的字符例外情况是#
、&
、@
谢谢!
I am trying to replace a string from an original text. ( zinc
--> zn
)
Example: 'zinc zinc zinc zinc3 !zinc zincmatic #zinc zinc9 Zinc @zinc@'
Want: 'zn zn zn zinc3 !zn zincmatic #zinc zinc9 zn @zinc@'
The str_ireplace attempt:
$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);
Prints zn zinc zn zinc3 !zinc zincmatic #zinc zinc9 zn @zinc@
. Still have problems as !zinc
and second zinc
remains due to space problems..
The preg_replace attempt:
$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;
Prints zn zn zn zinc3 !zn zincmatic #zn zinc9 zn @zn@
almost got what i want: seems that zinc will turn into zn
even if there is some special char near like !zinc
or #zinc
but not if there is a number zinc9
or text like zincmatic
I just want to put a rule here so that #zinc
keeps #zinc
, @zinc@
keeps @zinc@
and !zinc
turns to !zn
Is there a way to add some exceptions to special chars if zinc is near one of them ( ie : #zinc
, zinc#
, zinc@
, @zinc
)
The chars I want to be an execptions are #
, &
, @
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用否定断言来定义此类异常。它们的行为类似于
\b
并且实际上可以结合使用。在您的情况下,您希望
(? 探测前面的字符,并
(?![#&@])
进行测试以下字符。You can define such exceptions with negative assertions. They behave similar to
\b
and can in fact be used in conjunction.In your case you want
(?<![#&@])
to probe the preceding character, and(?![#&@])
to test the following character.