Php 如何创建添加到现有信息的函数?
我有一个包含字符串的现有代码。我需要能够创建一个函数,将添加到现有的字符串中。我正在努力学习如何在php中实现这一点。我是新来的,我以前查过的所有东西都让我一事无成 当一切都说了又做了,这就是我想要的: 向包含字符串的现有变量添加新词的函数。(以下是现有的文字代码) 以下是我所能想到的:Php 如何创建添加到现有信息的函数?,php,mysql,Php,Mysql,我有一个包含字符串的现有代码。我需要能够创建一个函数,将添加到现有的字符串中。我正在努力学习如何在php中实现这一点。我是新来的,我以前查过的所有东西都让我一事无成 当一切都说了又做了,这就是我想要的: 向包含字符串的现有变量添加新词的函数。(以下是现有的文字代码) 以下是我所能想到的: function newWord($word){ $newAlpha = 'Time Table'; if ($newAlpha > 0){ echo $newAlpha =>
function newWord($word){
$newAlpha = 'Time Table';
if ($newAlpha > 0){
echo $newAlpha => $words;
}
}
我知道这是不对的,但我对php和mysql非常陌生。可能值得注意的是,最终我需要将该函数插入到存放$words的数据库中,但如果有人能帮助我,这将是一个额外的功能。您只需使用concat操作符
$words = 'Apple Sauce, Tasty Chicken, New Monkey, Left Right';
$added_words = $words .'new_word_one, new_word_two, etc...';
var_dump($added_words);
// produces (string)"Apple Sauce, Tasty Chicken, New Monkey, Left Right new_word_one, new_word_two, etc..."
只需将其与字符串连接:
function newWord($word, $words){
if($word != ''){//or any other check you want
return "$words, $word";
}
return $words;
}
用法:
$newAlpha = 'Time Table';
$words = newWord($newAlpha,$words);//now $words has $newAlpha appended onto the end with comma and space
你可以在这里看到它的作用:
我考虑过这一点,但我希望在函数中输入新词,因为我需要在将其添加到现有的词组之前对其进行一些检查。我希望这是有意义的。我绿色检查了它,因为这是最好的答案,我正在使用它,但它仍然没有将单词附加到现有的单词中。知道为什么吗?我的意思是,新词不会出现,但代码会运行。这怎么可能呢?检查我添加到答案中的演示页面。哦,我明白了,你希望这个函数回显字符串的新版本?只需将return改为echo,但是你会丢失该变量的新值,因为如果你不返回它,它只存在于函数的作用域中。你是对的,我会根据需要不断调整它。谢谢
$newAlpha = 'Time Table';
$words = newWord($newAlpha,$words);//now $words has $newAlpha appended onto the end with comma and space
$words = 'Apple Sauce, Tasty Chicken, New Monkey, Left Right';
$new_plus_old_words = "$words new_word1, new_word2, new_word3";