gpt4 book ai didi

php - 随机替换字符串中的单词

转载 作者:行者123 更新时间:2023-12-03 21:42:52 26 4
gpt4 key购买 nike

我正在尝试编写一个脚本,该脚本将采用文本字符串并允许我替换随机单词。例如:

$str = "The quick brown fox jumps over the lazy dog";
我将输出为并替换如下几个词:

The quick ______ fox jumps over the ____ dog


我可以通过首先将字符串拆分为数组来做到这一点
$arr = str_word_count($str, 1);
然后替换 $arr[2]$arr[7] .
如果字符串中有非单词,我认为我会遇到的问题,比如标点符号:
$str = "The quick brown fox, named Jack, jumps over the lazy dog; and Bingo was his...";
我该如何解决这个问题?想法?

最佳答案

你可以这样做:

   $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
结果:
The quick brown fox, named test1, jumps over the lazy test2; and Bingo2 was his... 
它可以使用或不使用标点符号。
但请记住,如果您有 JackJacky例如,您需要添加额外的逻辑,例如使用 Regex to match only letters 检查标点部分是否没有任何字母。 ,如果确实跳过它,则表示它不是完全匹配。或舒缓类似。
编辑(基于评论):
$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;
结果:
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...

关于php - 随机替换字符串中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66394704/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com