仅当字符串为搜索时才替换字符串(preg_replace多字节) [英] Replace String only if string is search (preg_replace multibyte)
问题描述
我有问题.我只想替换某些与我键入的字符串完全相同的字符串.因此,如果字符串中带有5 Eur
,则只能用例如Steam 5 Euro
,如果他是一个人,而不是字符串是How are you 5 Eur pls
.
使用我的实际代码,这是不可能的...我使用例如:
$string = str_replace('Apple Itunes 25 Euro Guthaben Prepaid De', 'Apple iTunes 25 Euro', $string)
因为此处字符串包含25 Eur
,所以此代码还添加了一些内容:
$string = str_replace('25 Eur', 'Steam 25 Euro', $string);
但是如果我想使用preg_replace(/\b25 Eur\b/i)
,则会出现此错误:
PHP警告:preg_replace():中的未知修饰符'.'
所以我有两个问题:
-
如何使用多字节替换功能?
-
我如何才能告诉此函数仅替换一个单独的字符串(如果他是一个字符串)而不替换一个包含搜索到的字符串的字符串?
问候和谢谢!
这应该有效.
搜索依据:
^(25 Eur)$
替换为:
Steam 25 Euro
输入:
Apple Itunes 25 Euro Guthaben Prepaid De', 'Apple iTunes 25 Euro
25 Eur
输出:
Apple Itunes 25 Euro Guthaben Prepaid De', 'Apple iTunes 25 Euro
Steam 25 Euro
PHP代码:
<?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;
请参阅: https://regex101.com/r/3DKEas/2 >
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!
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
这篇关于仅当字符串为搜索时才替换字符串(preg_replace多字节)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!