PHP:如何替换字符串的段从列表中一些随机文本(PHP: How to replace a segm

2019-09-30 02:43发布

我有一个在它的URL字符串,我想查找和替换用别的东西URL的可预测部分。

基本上,如何随机化的子域的选择。

例如, $file包含: https://url.foo.com/w_Path/File.doc我如何检查是否$file包含url.foo.com ,如果是这样,则更换url.foo.com与部分要么differentsubdomain.foo.comanotherplace.foo.comsomeotherplace.foo.com

输入:

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

所需的输出:

$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

Answer 1:

把你随机要选择的值到一个数组,使用array_rand()选择一个随机元素(这将返回键,让你不得不选择再次根据你拿到了钥匙数组的值),然后使用str_replace()取代的值。

如果搜索字符串(“针”,你的情况url.foo.com未找到),无需更换会发生。 当心,如果发生一次以上,这将取代针的所有实例。

$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);
  • 在现场演示https://3v4l.org/um719

你也可以用array_flip()并使用array_rand()上,要达到相同的结果。

$random = array_rand(array_flip($random_values));
  • 在那个现场演示https://3v4l.org/X5KA3


文章来源: PHP: How to replace a segment of a string with some random text from a list