user632347
user632347

Reputation: 835

Search and replace a word in a string with an array

I want to scan a paragraph and replace needles in that with another word. for example

$needles = array('head', 'limbs', 'trunk');
$to_replace = "this";
$haystack = "Main parts of human body is head, Limbs and Trunk";

Final out put needed

Main part of human body is this, this and this

How can I do it?

Upvotes: 0

Views: 64

Answers (2)

Loic
Loic

Reputation: 540

With preg_replace :

$needles = array('head', 'limbs', 'trunk');
$pattern = '/' . implode('|', $needles) . '/i';
$to_replace = "this";
$haystack = "Main parts of human body is head, Limbs and Trunk";

echo preg_replace($pattern, $to_replace, $haystack);

Upvotes: 1

Antony
Antony

Reputation: 15104

Assuming you are using PHP, you can try str_ireplace.

$needles = array('head', 'limbs', 'trunk');
$to_replace = "this";
$haystack = "Main parts of human body is head, Limbs and Trunk";
echo str_ireplace($needles, $to_replace, $haystack); // prints "Main parts of human body is this, this and this"

Upvotes: 1

Related Questions