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

Any updates please :)

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.