php - Finding and Replacing String and characters around it -
stackoverflow.
let's have variable:
$paragraph = "this bunch of random information. here url: http://example.com/inventory/personid checking out!"; i need detect if $paragraph has url in it, if personid changes, , save variable, replace new code. example, should walk away with:
$url = "http://example.com/inventory/personid"; $replace = "newinformation!"; $newparagraph = "this bunch of random information. here url: newinformation! checking out!"; i'm pretty sure has strpos(), have no idea past that.
edit: personid represented along lines of #730_2_1697061248 numbers change.
just use preg_replace(), replace url:
echo $newparagraph = preg_replace("/\b" . preg_quote($url, "/") . "\s*/", $replace, $paragraph); output:
this bunch of random information. here url: newinformation! checking out! regex explanation:
/\b . preg_quote($url, "/") . \s* - \b assert position @ word boundary (^\w|\w$|\w\w|\w\w) test matches characters test literally (case sensitive)
- preg_quote($url, "/") ->
http\:\/\/example\.com\/inventory\/ - \s* match non-white space character [^\r\n\t\f ]
- quantifier: * between 0 , unlimited times, many times possible, giving needed [greedy]