2011-02-22 104 views
0

我在PHP中有一个基本的字符串问题。在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

阅读str这是基本的PHP http://php.net/manual/en/language.types.string.php – 2011-02-22 03:50:49

回答

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); 

参见:

如果您在使用PHP与HTML和要打印的字符串(PHP之外的标签)

this story is titled <?php echo $title ?> and it is really good 
+0

+1为详细的答案与手册主题的链接 –

+0

感谢您的简单解释,我忘了提到,我想这样做,而不创建一个新的变量。感谢大家的帮助! –

0

你只需要使用双引号,把变量里面的字符串,像这样:

$title = 'candy'; 
$story = "this story is titled $title and it is really good"; 
+0

也''故事='这个故事的标题是'。 $ title。'真的很好'; ' – Moak

+0

嗯,在我看到这个之前,我已将这部分添加到了我的评论中 - 现在它已被删除? – GreenWebDev

+0

这个解决方案假定'$ title'是在'$ story'之前定义的,这可能并非总是如此。 –

0

我建议在原始字符串中使用占位符,然后来替代占位符你的题目。

因此,修改你的代码是这样的:

$story = "this story is titled {TITLE} and it is really good"; 

然后,您可以使用str_replace与实际所有权,以取代占位符,如:

$newStory = str_replace("{TITLE}", $title, $story); 
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); 
0

把你的朋友的字符串插值的优势(如GreenWevDev said)。

或者,如果您需要用字符串替换单词title,并且只能自行使用正则表达式。

$story = preg_replace('/\btitle\b/', $title, $story);