查找并替换它周围的字符串和字符

时间:2015-04-10 00:45:06

标签: php html

的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的行,但数字会改变。

1 个答案:

答案 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*
  • \ b 在字边界处断言位置(^ \ w | \ w $ | \ W \ w | \ w \ W) test字面测试匹配字符(区分大小写)
  • preg_quote($ url,“/”) - > http\:\/\/example\.com\/inventory\/
  • \ S * 匹配任何非空格字符[^ \ r \ n \ t \ f]
    • 量词: * 在零和无限次之间,尽可能多次,根据需要回馈[贪婪]