我有一个函数用数组替换每个字符:
function z3($str){
$text=$str;
$sr = array(
'a' => array('A'),
'b' => array('B'),
' ' => array(' ')
);
for ($i = 0, $len = strlen($text); $i < $len; $i++) {
$news .= $sr[$text[$i]][@array_rand($sr[$text[$i]])];
}
$nn=$news;
return $nn;
}
echo z3("aaa");
我需要开发它,如果角色(a
)在最后一个单词中,并且在它是空格之后,我想向它添加('s
)。让我解释一下:
$str = "aaa aaa aaa";
echo z3($str);
我需要输出为AAA's AAA's AAA
。
答案 0 :(得分:1)
很难理解你的问题,但如果你只想在最后一个字符为 a 的单词中添加撇号,你需要将除的之外的所有内容都大写你不想让最后一句话占有欲......
function z3($str) {
$parts = explode(' ', $str);
for ($i=0; $i < count($parts); $i++) {
$parts[$i] = strtoupper($parts[$i]);
if (substr($parts[$i], -1) == 'A') {
$parts[$i] = $parts[$i] . "'s";
}
}
$str = implode(' ', $parts);
return rtrim($str, "'s");
}
$str = "aaa aaa aaa";
echo z3($str); // outputs AAA's AAA's AAA
答案 1 :(得分:0)
str_replace(" ", "'s ", trim($str))
答案 2 :(得分:0)
function z3($str) {
$sr = array(
'a' => array('A'),
'b' => array('B'),
' ' => array(' ')
);
$nn = '';
for ($i = 0, $len = strlen($str); $i < $len; $i++) {
if($str[$i] == ' ' && isset($str[$i-1]) && $str[$i-1] == 'a')
$nn.= "'s";
$nn.= $sr[$str[$i]][@array_rand($sr[$str[$i]])];
}
return $nn;
}
$str = "aaa aaa aaa";
echo z3($str);
答案 3 :(得分:0)
你想(1)将每个字符更改为$ sr数组中的相应值,(2)如果单词包含'a'而不是最后一个字,则在单词的末尾添加“'s”
尝试:
function z3(&$str) {
$sr = array(
'a' => array('A'),
'b' => array('B'),
' ' => array(' ')
);
$words = explode(' ', $str); // split str into words
$numwords = count($words);
foreach ($words as $index => &$word) { // run through each word
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY); // split word into characters
foreach ($chars as &$char) { // run through each character
if (array_key_exists($char, $sr)) {
$char = $sr[$char]; // if there is a replacement in $sr array, set $char to its value
}
}
if ($index < $numwords && in_array($sr['a'], $chars) { // if this is not the last word and it contains an 'a', append characters ' and s
$chars += array("'", "s");
}
$word = implode('', $chars); // pull the words back together
}
$str = implode(' ', $words); // pull the string back together
}
$str = 'aaa aaa aaa';
z3($str);
echo $str; // echoes AAA's AAA's AAA
答案 4 :(得分:0)
function z3($str) {
$patt=str_split("ab");
$repl=str_split("AB");
return preg_replace("/ /", "'s ", str_replace($patt, $repl, $str));
}
$str="bar tab";
echo z3($str);
>>> BAr's tAB