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

时间:2016-03-31 02:29:13

标签: php replace file-get-contents

与朋友一起玩愚人节笑话。基本上,我们是file_get_contents();本地报纸文章,并针对特定名称和图片网址执行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等。我不知道取代的是什么,如果我能获得更多,我可以弄清楚细节而不是一个搜索/替换。

谢谢!

2 个答案:

答案 0 :(得分:1)

要进行考虑语法和自然语言的复杂替换,你需要更复杂的东西。但是对于简单的搜索和替换,这可以正常工作:

<?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

答案 1 :(得分:1)

@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