Username:   Password:  

Search and replace string recursively in C#

static void ProcessDir(string path, string search, string replace)
{
    // First access subdirectories
    string[] subDirs = Directory.GetDirectories(path);
 
    foreach (string curSubDir in subDirs)
    {
        ProcessDir(Path.Combine(path, curSubDir));
    }
 
    // Now process files
    string[] files = Directory.GetFiles(path, "*.txt");
 
    foreach(string curFile in files) {
        ProcessFile(Path.Combine(path, curFile), search, replace);
    }
}
 
private static void ProcessFile(string path, string search, string replace)
{
    StreamReader input = new StreamReader(path);
    string content = input.ReadToEnd();
    input.Close();
 
    content = Regex.Replace(content, search, replace);
 
    try
    {
        StreamWriter output = new StreamWriter(path);
        output.Write(content);
        output.Close();
    }
    catch (IOException)
    {
        Console.WriteLine("Skipping file " + path);
        return;
    }
}

Searches recursively for *.txt files in a directory and subdirectories and replaces all occurences of "string search" with "string replace"

Tags

search replace C# CSharp .NET Regex Regual Expressions

Extract the search term from google referer

$referer = strtolower($_SERVER['HTTP_REFERER']);
 
// Test if user comes from google
if (strpos($referer, 'google')) {
	// Delete all before &q=
    $tmp = substr($referer, strpos($referer, 'q='));		
 
    // Remove q=
	$tmp = substr($tmp, 2);
 
	// Remove everything after the next &
	if (strpos($tmp, '&')) {
		$tmp = substr($tmp, 0,strpos($tmp, '&'));
	}	
	// we have the results.
	$searchTerm = urldecode($tmp);
}

Takes the referer and extracts the search term, if user comes from google.

Tags

google php referer keyword search term