1

I have a string with a URL in it and I wish to find and replace a predictable part of the URL with something else.

Basically, how to randomise a choice of subdomain.

For example, $file contains: https://url.foo.com/w_Path/File.doc how do I check if $file contains url.foo.com, and if so, replace the url.foo.com portion with either differentsubdomain.foo.com or anotherplace.foo.com or someotherplace.foo.com?

Input:

$file = "https://url.foo.com/w_Path/SomeFile.ext";
$params['file'] = $file

Desired output:

$file = "https://url.foo.com/w_Path/SomeFile.ext";
 // list of subdomains = "differentsubdomain", "anotherplace", "someotherplace";
 // find 'url.foo.com' part of $file and replace with random subdomain choice from list
 // $file = "https://someotherplace.foo.com/w_Path/SomeFile.ext";
$params['file'] = $file

1 Answer 1

1

Put the values you randomly want to select into an array, use array_rand() to pick a random element (this returns the key, so you have to select the value from the array again based on the key you got), then use str_replace() to replace the value.

If the search-string ("needle", in your case url.foo.com) is not found, no replacement will happen. Beware, that this will replace all instances of that needle if it occurs more than once.

$random_values = ['differentsubdomain.foo.com', 'anotherplace.foo.com', 'someotherplace.foo.com'];
$random = $random_values[array_rand($random_values)];


$file = "https://url.foo.com/w_Path/SomeFile.ext";
$file = str_replace('url.foo.com', $random, $file);

You can also use array_flip(), and use array_rand() on that to achieve the same result.

$random = array_rand(array_flip($random_values));
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, just put that code in a loop that loops over all the relevant files (which is represented by elements in the array)
Can't really be more specific without seeing the structure of the array.
Just loop over it, pass by reference (the & in the foreach) and edit. 3v4l.org/TcP5S

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.