1

I'm trying to replace words in a string with words from an array. Problem is the result repeated multiple times. I know there is a gotcha for str_replace, but i can't find any solution for this problem.

I tried with str_replace and preg_replace.

My codes:

With str_replace:

$text = 'Amir and Mahdi are friends.';
$text2 = str_replace(array("Amir","Mahdi"), '{Amir|Mahdi}', $text);

Result: {Amir|{Amir|Mahdi}} and {Amir|Mahdi} are friends.


With preg_replace:

$text = 'Amir and Mahdi are friends.';
$text2 = preg_replace(array("/Amir/","/Mahdi/"), '{Amir|Mahdi}', $text);

Result: {Amir|{Amir|Mahdi}} and {Amir|Mahdi} are friends.


I want this result: {Amir|Mahdi} and {Amir|Mahdi} are friends.

0

1 Answer 1

1

with replace patter as array it first converts {Amir|Mahdi} and Mahdi are friends., again for arrays second index Mahdi it converts both Mahdi. That's why I suggest you to use | (OR) condition in pattern instead of array.

$text = 'Amir and Mahdi are friends.';
$text2 = preg_replace("/Amir|Mahdi/", '{Amir|Mahdi}', $text);
echo $text2;

Working demo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.