问题
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 Eur
he 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:
How can I use an multibyte replace function?
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