2011-02-22 107 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);