4

i use this line to search for a name in text with url's.

$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 the text

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

I’d be very interested in the more accurate solution that you were suggesting. I think PHP now supports everything necessary. I’ve tried /(?<!http:\/\/[^ ])+\bxxx\b/i but that only matches whole words, separated by spaces, but not yxxxy or xxxy. Any hint would be much appreciated. And https support would be handy, too. Can’t wrap my head around the logic here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.