我正在尝试编写一个脚本,该脚本将使用文本字符串,并允许我替换随机单词。例如:
$str = "The quick brown fox jumps over the lazy dog";
我将把as替换成这样的几个词:
敏捷的______狐狸跳过了____狗
我可能可以通过首先将字符串拆分为数组来做到这一点
$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...
它可以带或不带标点符号。
但是请记住,如果有Jack
,Jacky
例如您将需要添加其他逻辑,例如使用Regex检查标点部分中是否没有任何字母以仅匹配字母,如果确实跳过它,则表示它不完全匹配。或舒缓类似。
编辑(基于评论):
$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...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句