在 PHP 中一次替换多个不同单词的更好方法
Better way to replace multiple different words at once in PHP
我编写 file_get_contents 代码已经有一段时间了,我真的厌倦了使用我的方法一次替换多个不同的单词。有时我 file_get_contents 来自的网站更改了布局,因此必须在所有这些混乱中进行更改。
这是我正在使用的方法:
$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 必须处理如此混乱的额外延迟
是的,您可以通过发送数组来实现:
$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
);
我编写 file_get_contents 代码已经有一段时间了,我真的厌倦了使用我的方法一次替换多个不同的单词。有时我 file_get_contents 来自的网站更改了布局,因此必须在所有这些混乱中进行更改。
这是我正在使用的方法:
$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 必须处理如此混乱的额外延迟
是的,您可以通过发送数组来实现:
$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
);