Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

php - Replace String only if string is search (preg_replace multibyte)

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(/25 Eur/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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...