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

StackOverflow.

Let's say I have this variable:

$paragraph = "This is a bunch of random information. Here is a URL: http://example.com/inventory/personid Thanks for checking it out!";

I need to detect if the $paragraph has a URL in it, even if the personid changes, and then save it as a variable, then replace it with some new code. For example, this is what I should walk away with:

$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!";

I'm pretty sure this has to do with strpos(), but I have no idea past that.

Edit: personid would be represented as something along the lines of #730_2_1697061248 but the numbers would change.

Just use preg_replace(), like this to replace the url:

echo $newparagraph = preg_replace("/\b" . preg_quote($url, "/") . "\S*/", $replace, $paragraph);

output:

This is a bunch of random information. Here is a URL: newinformation! Thanks for checking it out!

regex explanation:

/\b . preg_quote($url, "/") . \S*
  • \b assert position at a word boundary (^\w|\w$|\W\w|\w\W) test matches the characters test literally (case sensitive)
  • preg_quote($url, "/") -> http\:\/\/example\.com\/inventory\/
  • \S* match any non-white space character [^ \t\f ]
    • Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]