使用搜索替换多个文件获取内容参数


Using Search Replace for Multiple File Get Contents Param

和朋友开愚人节玩笑。基本上,我们是file_get_contents();(一篇本地报纸文章),并为特定的名称和图像URL执行str_replace();。我们要替换什么都无关紧要,我面临的问题是执行多个搜索/替换值。

我写了两个函数,每个函数都有自己的变量和搜索/替换,只有第一个有效。我正在为如何获得多个搜索/替换值而绞尽脑汁。下面是我正在使用的基本代码。如何添加多个搜索/替换?

// Let's April Fool!
$readfile = 'URL-police-searching-for-bank-robbery-suspect';
$pull = file_get_contents($readfile);
$suspectname = 'Suspect Name';
$newname = 'New Name';
echo str_replace($suspectname, $newname, $pull);

我想搜索/替换页面上的内容,如名称、img src URL等。我要替换什么并不重要,如果我能得到多个搜索/替换,我可以计算出细节。

谢谢!

要进行考虑语法和自然语言的复杂替换,需要更复杂的东西。但对于简单的搜索和替换,这将很好:

<?php
$pull = "the suspect was last seen wearing a black hoodie and trainers. Have you seen this man? www.local_police.com/bank_robber.jpg";
echo $pull . "'n";
$dictionary = array("the suspect" => "friend_name", "hoodie" => "swimsuit", "trainers" => "adult diaper", "www.local_police.com/bank_robber.jpg" => "www.linkedlin.com/friend_profile_pic.jpg" );
foreach ($dictionary as $key => $value){
    $pull = str_replace($key, $value, $pull);
}
echo $pull . "'n";
?>

输出:

user@box:~/$ php prank.php 
the suspect was last seen wearing a black hoodie and trainers. Have you seen this man? www.local_police.com/bank_robber.jpg
friend_name was last seen wearing a black swimsuit and adult diaper. Have you seen this man? www.linkedlin.com/friend_profile_pic.jpg

@jDo回答了我的问题,让我开始了,但我想分享最终产品。以下是我的想法:

//
// Using file_get_contents(); in an array   
//
//
// Define the file we want to get contents from in a variable
//
$readfile = 'http://adomainname.com/page/etc';
//
// Variable to read the contents of our file into a string
//
$pull = file_get_contents($readfile);
//
//
// Define stuff to be replaced
//
$find_stuff = 'Find Stuff';
$replace_stuff = 'Replace Stuff';
$find_more_stuff = 'Find More Stuff';
$replace_more_stuff  = 'Replace More Stuff';
//
// Variable to create the array that stores multiple values in one single variable
//
$find_replace = [ // Let's start our array
                $find_stuff => $replace_stuff,
                $find_more_stuff => $replace_more_stuff,
                ];// Close the array
//
// This is where the magic happens
//
foreach ($find_replace as $key => $value){ // Now we take our array of each key and value
$pull = str_replace($key, $value, $pull); // Will look for matched keys and replace them with our new values 
}
echo $pull; // That's it