2017-05-15 10 views
1

私は今file_get_contentsコードをしばらく行っていますが、私のメソッドを使って一度に複数の異なる単語を置き換えることには疲れています。時には私がfile_get_contentsのサイトがレイアウトを変更したため、この混乱の中で変更する必要があります。PHPで一度に複数の異なる単語を置き換えるより良い方法

これは私が使用している方法である:

$results = file_get_contents('https://example.com/'); 

$filter1 = str_replace('https://example.com', 'index.php',  $results); 
$filter2 = str_replace('<script', '<!-- OVERWRITTEN ',   $filter1); 
$filter3 = str_replace('</script>', ' OVERWRITTEN -->',   $filter2); 
$filter4 = str_replace('src="http://example.com', 'src="',  $filter3); 
$output = str_replace('<p>Some Text</p>', '<p>Something Else</p>',$filter4); 

echo $output; 

は、それは私が行っているよりも、一度に複数の異なる単語を交換するより良いとクリーンな方法ですか?私はあなたが配列で送信することによって、それを行うことができ、PHPは、このような混乱を

+0

多分配列を使用していますか?配列をループしてstr_replaceしますか? – gabs

+0

@gabs私は本当にループを避けたいですが、配列が何かになる可能性があります。 – Typewar

+0

@Typewar Yea、配列FTW。私のソリューションは機能しますか? –

答えて

1

うんを処理しなければならない余分な遅延についてはよく分からない:

$results = file_get_contents('https://example.com/'); 

$output = str_replace(
    array('https://example.com', '<script', '</script>', 'src="http://example.com', '<p>Some Text</p>'), 
    array('index.php', '<!-- OVERWRITTEN ', ' OVERWRITTEN -->', 'src="', '<p>Something Else</p>'), 
    $results 
); 

echo $output; 

明確にするために、交換するコードは次のとおりです。

$output = str_replace(
    array('https://example.com', '<script',   '</script>',  'src="http://example.com', '<p>Some Text</p>'), 
    array('index.php',   '<!-- OVERWRITTEN ', ' OVERWRITTEN -->', 'src="',     '<p>Something Else</p>'), 
    $results 
); 
関連する問題