我在PHP中有一个基本的字符串问题。
假设我有一个变量$story
:
$story = 'this story is titled and it is really good';
如何在'标题'之后和'和'之前添加字符串? 如果我在另一个变量中有标题,那么就说
$title = 'candy';
我可以用什么功能或方法来做这件事?
$story = 'this story is titled and it is really good';
$title = 'candy';
// do something
var_dump($story === 'this story is titled candy and it is really good'); // TRUE
答案 0 :(得分:6)
有几个选择。
$title = 'candy';
$story = 'this story is titled '.$title.' and it is really good';
$story = "this story is titled $title and it is really good";
$story = sprintf('this story is titled %s and it is really good', $title);
请参阅:
如果您使用带有html的php并且想要打印字符串(在php标签之外)
this story is titled <?php echo $title ?> and it is really good
答案 1 :(得分:0)
你只需要使用双引号并将变量放在字符串中,如下所示:
$title = 'candy';
$story = "this story is titled $title and it is really good";
答案 2 :(得分:0)
我建议您在原始字符串中使用占位符,然后将占位符替换为您的标题。
所以,修改你的代码是这样的:
$story = "this story is titled {TITLE} and it is really good";
然后,您可以使用str_replace将占位符替换为实际标题,如下所示:
$newStory = str_replace("{TITLE}", $title, $story);
答案 3 :(得分:0)
简单的方法是:
$story="this story is titled $title and it is really good".
如果你问如何找到插入位置,可以这样做:
$i=stripos($story," and");
$story=substr($story,0,$i)." ".$title.substr($story,$i);
第三个是放置一个不太可能出现在文本中的标记,如|| TITLE ||。搜索并将其替换为标题文本,如:
$i=stripos($story,"||TITLE||");
$story=substr($story,0,$i).$title.substr($story,$i+9);
答案 4 :(得分:0)
利用您的朋友字符串插值(GreenWevDev said)。
或者,如果您需要将单词title
替换为字符串,并且只能单独替换,则可以使用正则表达式。
$story = preg_replace('/\btitle\b/', $title, $story);