0

I use a preg_replace to auto insert HTML links within paragraphs.

Here's what I currently use:

$pattern = "~(?!(?:[^<\[]+[>\]]|[^>\]]+<\/a>))(".preg_quote($find_keyword, '/').")\b~msUi";
$replacement = "<a href=\"http://$kw_url\" title=\"$find_keyword\">\$0</a>"; 
$article_content = preg_replace($pattern, $replacement, stripslashes($article_content), 1, $added );

It works great, except 1 problem:

It doesn't match and replace if the keyword is a URL.

If: $find_keyword="http://www.mysite.com/" it won't come up with any matches even though it's in the content.

I already tried escaping $find_keyword with preg_quote, which didn't make any different.

Any regex experts know a solution? Thanks.

5
  • I already tried escaping forward slashes, which didn't make any different. Commented Mar 28, 2011 at 19:43
  • 2
    What happens if you pass $find_keyword through preg_quote() (as you should with all input to regex)? Commented Mar 28, 2011 at 19:45
  • Have you thought about users that link to http://example.com/"<script>alert("xss")</script> ? Commented Mar 28, 2011 at 19:46
  • No change when I try: $pattern = "~(?!(?:[^<\[]+[>\]]|[^>\]]+<\/a>))(".preg_quote($find_keyword).")\b~msUi"; Commented Mar 28, 2011 at 19:48
  • @user, all HTML tags are stripped from the original content. Commented Mar 28, 2011 at 19:49

2 Answers 2

1

The forward slashes in your $find_keywords are not escaped which is breaking the pattern.

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

1 Comment

Read the comments. They were escaped and it didn't make a difference.
0

You can run your find_keyword through

$find_keyword=preg_quote("http://www.mysite.com/", '/');

http://www.php.net/manual/en/function.preg-quote.php

1 Comment

Please post sample $article_content input and your desired output.

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.