的StackOverflow。
假设我有这个变量:
$paragraph = "This is a bunch of random information. Here is a URL: http://example.com/inventory/personid Thanks for checking it out!";
我需要检测$段落中是否有URL,即使personid
发生了变化,然后将其保存为变量,然后将其替换为一些新代码。例如,这就是我应该离开的地方:
$url = "http://example.com/inventory/personid";
$replace = "newinformation!";
$newparagraph = "This is a bunch of random information. Here is a URL: newinformation! Thanks for checking it out!";
我很确定这与strpos()有关,但我不知道过去。
编辑:personid将被表示为#730_2_1697061248
的行,但数字会改变。
答案 0 :(得分:0)
只需使用preg_replace()
,就像这样替换网址:
echo $newparagraph = preg_replace("/\b" . preg_quote($url, "/") . "\S*/", $replace, $paragraph);
输出:
This is a bunch of random information. Here is a URL: newinformation! Thanks for checking it out!
正则表达式解释:
/\b . preg_quote($url, "/") . \S*
http\:\/\/example\.com\/inventory\/