PHP:如何用列表中的随机文本替换字符串的一段
我有一个包含URL的字符串,我希望找到URL的可预测部分,并用其他内容替换它 基本上,如何随机选择子域 例如,PHP:如何用列表中的随机文本替换字符串的一段,php,string,replace,Php,String,Replace,我有一个包含URL的字符串,我希望找到URL的可预测部分,并用其他内容替换它 基本上,如何随机选择子域 例如,$file包含:https://url.foo.com/w_Path/File.doc如何检查$file是否包含url.foo.com,如果是,将url.foo.com部分替换为differentitsubdomain.foo.com或anotherplace.foo.com或someotherplace.foo.com 输入: 期望输出: 将随机要选择的值放入数组,使用array\u
$file
包含:https://url.foo.com/w_Path/File.doc
如何检查$file
是否包含url.foo.com
,如果是,将url.foo.com
部分替换为differentitsubdomain.foo.com
或anotherplace.foo.com
或someotherplace.foo.com
输入:
期望输出:
将随机要选择的值放入数组,使用
array\u rand()
拾取随机元素(这将返回键,因此必须根据获得的键再次从数组中选择值),然后使用str\u replace()
替换值
如果没有找到搜索字符串(“针”,在您的例子中是url.foo.com
),则不会进行替换。注意,如果针不止一次出现,这将替换该针的所有实例
$random_values=['differentitsubdomain.foo.com','anotherplace.foo.com','someotherplace.foo.com'];
$random=$random_值[数组_rand($random_值)];
$file=”https://url.foo.com/w_Path/SomeFile.ext";
$file=str_replace('url.foo.com',$random,$file);
- 现场演示
array\u flip()
,并在其上使用array\u rand()
,以获得相同的结果
$random = array_rand(array_flip($random_values));
- 现场演示
&
)并进行编辑。
$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
$random = array_rand(array_flip($random_values));