Replace String only if string is search (preg_replace multibyte)

六月ゝ 毕业季﹏ 提交于 2019-12-12 03:35:33

问题


I have a problem. I want to replace certain strings only if they are exactly like I typed. So if there is a string with 5 Eurhe should only be replaced with e.g. Steam 5 Euro, if he stands alone and not if the string is like How are you 5 Eur pls.

With my actual code this is not possible... I use e.g.:

$string = str_replace('Apple Itunes 25 Euro Guthaben Prepaid De', 'Apple iTunes 25 Euro', $string)

Because here the string contains 25 Eur this code is also adding some stuff:

$string = str_replace('25 Eur', 'Steam 25 Euro', $string);

But if I want to use preg_replace(/\b25 Eur\b/i) I get this error:

PHP Warning: preg_replace(): Unknown modifier '�' in

So I have two questions:

  1. How can I use an multibyte replace function?

  2. How can I tell this function only to replace a certain string if he stands alone and not if he contains the searched string?

Greetings and Thank You!


回答1:


This Should Work.

Search by:

^(25 Eur)$

Replace with:

Steam 25 Euro

Input:

Apple Itunes 25 Euro Guthaben Prepaid De', 'Apple iTunes 25 Euro
25 Eur

Output:

Apple Itunes 25 Euro Guthaben Prepaid De', 'Apple iTunes 25 Euro
Steam 25 Euro

PHP Code:

<?php
$re = '/^(25 Eur)$/m';
$str = 'Apple Itunes 25 Euro Guthaben Prepaid De\', \'Apple iTunes 25 Euro
25 Eur';
$subst = 'Steam 25 Euro';

$result = preg_replace($re, $subst, $str);

echo "The result of the substitution is ".$result;

See: https://regex101.com/r/3DKEas/2



来源:https://stackoverflow.com/questions/42401062/replace-string-only-if-string-is-search-preg-replace-multibyte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!