replace words in text ignore urls
i use this line to search for a name in text with url's.
$name开发者_StackOverflow社区 = "xxx";
$text = "my name is xxx en my website is http://xxx.something.com";
$text = preg_replace("/\b(".preg_quote($name, "/").")\b/i", $url, $text);
how can i change this regex to ignore urls in the text
1) You can use a regex to find all urls (e.g., http://snipplr.com/view/2371/regex-regular-expression-to-match-a-url/) - remember their positions and length
2) use your regex to find all the occurences of a word and also remember positions and length
3) go through results of 2) and check if the word is not in a url.
Not exactly what you're looking for but may be this help:
Replace xxx
with yyy
if and only if xxx
is surrounded by spaces or if it is at the start or end of the string.
<?
$name = "xxx";
$text = "xxx my name is xxx en my website xxx is http://xxx.something.com xxx";
$text = preg_replace("%(?<=^| )".$name."(?= |$)%i", "yyy", $text);
echo $text."\n";
//yyy my name is yyy en my website yyy is http://xxx.something.com yyy
?>
It would have been easier if PHP supported variable length look behind assertions; because then we could have used a more accurate (?<!http://[^ ]+)\bxxx\b
精彩评论