Replace words in text ignore urls

I use this string to search for a name in the text with a url.

$name = "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 text

+4
source share
2 answers

1) You can use a regular expression to search for all URLs (for example, http://snipplr.com/view/2371/regex-regular-expression-to-match-a-url/ ) - remember their position and length

2) use your regular expression to find all occurrences of the word, as well as remember the position and length

3) go through the results 2) and check to see if the word is in the URL.

+1
source

Not quite what you are looking for, but this help may be:

Replace xxx with yyy if and only if xxx is surrounded by spaces or if it is at the beginning or end of a line.

 <? $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 be easier if PHP support supported variable length outside of statements; because then we could use a more accurate (?<!http://[^ ]+)\bxxx\b

+1
source

Source: https://habr.com/ru/post/1313625/


All Articles