次のような文字列の場合:
むかしむかし、小さな若い LKTgoblingLKT が不幸な事故に遭い、LKTfellLKT が発生しました。
LKT
内部に含まれるコンテンツの各出現を配列に抽出し、それらを文字列に置き換えるにはどうすればよいですか。
次の解決策を試すことができます。
explode()
区切り文字としてスペースを含む文strpos()
このようなもの:
$string = '...';
$words = explode(' ', $string);
foreach ($words as $word) {
if (strpos($word, 'LKT') !== FALSE) {
$result[] = $word;
}
}
print_r($result);
出力:
Array
(
[0] => LKTgoblingLKT
[1] => LKTfellLKT.
)
文字列を別の単語に置き換えたい場合は、次のようにstr_replace()
andを使用できます。implode()
$string = '...';
$words = explode(' ', $string);
$result = array();
foreach ($words as $word) {
if (strpos($word, 'LKT') !== FALSE) {
$word = str_replace($word, 'FOO', $word);
}
$result[] = $word;
}
$resultString = implode(' ', $result);
echo $resultString;
出力:
Once upon a time a small young FOO had an unfortunate accident and FOO