0

Recently i was Writing a Preg replace Function in PHP
Here is the Code below

$suchmuster = "/".$textlinksname."/i";
$replace = "<a href='".$textlinksurl."' target='_blank'>".$textlinksname."</a>";
$body = preg_replace($suchmuster,$replace,$body,200);

Since the variable $body contains links begins with http:// when it replaces the matched text in URL it becomes a problem
Similarly for the images too

So is there any way to skip the text containing http:// using preg replace function ?

Here's an example

$textlinksname = 'Google';
$textlinksurl = 'http://google.com';
$body = 'Google is a great search engine. Here is the logo of it <img src =\'http://google.com/logo.jpg\'>';

$suchmuster = "/".$textlinksname."/i";
$replace = "<a href='".$textlinksurl."' target='_blank'>".$textlinksname."</a>";
$body = preg_replace($suchmuster,$replace,$body,200);

// Here the Output will be
// <a href='http://google.com' target='_blank'>Google</a> is a great search engine. Here is the logo of it <img src ='http://<a href='http://google.com' target='_blank'>Google</a>.com/logo.jpg'>
// It replaces the Word 'Google' even in the URL(Image) as result the links and image links get broken



// So, I expect the output must be like this
//<a href='http://google.com' target='_blank'>Google</a> is a great search engine. Here is the logo of it <img src ='http://google.com/logo.jpg'>
// Such that It replaces only text and skip the text in the URL's

Thanks

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by SikoSoft
0

Have you tried using the word-boundary character in your regular expression? Like this:

$suchmuster = "/\b".$textlinksname."\b/i";

That tells the regular expression that it only will match the given phrase if it is a isolated as its own word. In other words, it should catch google in this sentence:

Google is a search engine.

But it shouldn't catch google here:

www.google.com is the website address.

I would try using the \b character first in your regular expression to see if it works out then and there. I can't say for certain because I don't remember all the characters it uses to separate "words", but I think there's a good chance it will work.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.