2011-02-22 42 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 –

答えて

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 
+0

+1の詳細な答えは、手動のトピックへのリンク –

+0

簡単な説明のためにありがとう、私は新しい変数を作成せずにそれをやりたかったことを忘れていた。誰も助けてくれてありがとう! –

0

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

また '$ story = 'この物語はタイトルです'。 $タイトル。'それは本当に良いです'; ' – 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); 
関連する問題