开发者

The str_ireplace and preg_replace attemt?

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 o开发者_Go百科r 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!


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.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜