You can do it like this:
$test1 = "test1";
$test2 = "test2";
$test3 = "Bingo2";
// set new words
$str = "The quick brown fox, named Jack, jumps over the lazy dog; and Bingo was his...";
$re = explode(" ", $str);
// split them on space in array $re
echo $str . "<br>";
$num = 0;
foreach ($re as $key => $value) {
echo $value . "<br>";
$word = "";
switch (true) {
case (strpos($value, 'Jack') !== false):
// cheak if each value in array has in it wanted word to replace
// and if it does
$new = explode("Jack", $value);
// split at that word just to save punctuation
$word = $test1 . $new[1];
//replace the word and add back punctuation
break;
case (strpos($value, 'dog') !== false):
$new1 = explode("dog", $value);
$word = $test2 . $new1[1];
break;
case (strpos($value, 'Bingo') !== false):
$new2 = explode("Bingo", $value);
$word = $test3 . $new2[1];
break;
default:
$word = $value;
// if no word are found to replace just leave it
}
$re[$num++] = $word;
//push new words in order back into array
};
echo implode(" ", $re);
// join back with space
Result:
The quick brown fox, named test1, jumps over the lazy test2; and Bingo2 was his...
It works with or without punctuation.
But keep in mind if you have Jack
and Jacky
for example you will need to add additional logic such as checking if punctuation part does not have any letters in it with Regex to match only letters, if it does skip it, it means it was not full match. Or soothing similar.
EDIT (based on comments):
$wordstoraplce = ["Jacky","Jack", "dog", "Bingo","dontreplace"];
$replacewith = "_";
$word = "";
$str = "The quick brown fox, named Jack, jumps over the lazy dog; and Bingo was his...";
echo $str . "<br>";
foreach ($wordstoraplce as $key1 => $value1) {
$re = explode(" ", $str);
foreach ($re as $key => $value) {
if((strpos($value, $value1) !== false)){
$countn=strlen($value1);
$new = explode($value1, $value);
if (!ctype_alpha ($new[1])){
$word = " " . str_repeat($replacewith,$countn) . $new[1]. " ";
}else{
$word = $value;
}
}else{
$word = $value;
};
//echo $word;
$re[$key] = $word;
};
$str = implode(" ", $re);
};
echo $str;
RESULT:
The quick brown fox, named Jack, jumps over the lazy dog; and Bingo was his...
The quick brown fox, named ____, jumps over the lazy ___; and _____ was his...