I want to replace a part of a string but ignore some other parts of it. I have pattern but don't know how to use it.

$message = '<div class="sacred">http://www.daniweb.com/ is inside the div tag so I do not want it replaced.</div>http://www.google.com/ is outside the div tag so I do want it replaced';
$exclude = '<div class=\"sacred\">.*?<\/div>';
$pattern = '/(https?\:\/\/.*?\..*?)(?=\s|$)/i';
$message= preg_replace($pattern, '<a href="$1" target="_blank">$1</a>$2', $message);

How do I tell preg_replace to ignore everything that is in the <div class="sacred">....</div> parts of the string?

Thanks in advance.

Recommended Answers

All 3 Replies

Hi,

tell me if i understand* well what you ask:

you want the part of string that is in <div class="sacred">....</div> to be not treated
by preg_replace, so that there is no changement to this part.

I'm gonna try something and I'll be back to tell you if i have a solution to propose to you.


* I'm not anglophone, i'm french :-)

Rehi,

well, i've found a way to do what you want, it works but it's not really lightweight... Probably it's possible to do it with just one preg_replace, but i don't know how.

So i propose you this:

<?php
$message = '<div class="sacred">http://www.daniweb.com/ is inside the div tag so I do not want it replaced.</div>http://www.google.com/ is outside the div tag so I do want it replaced';
$pattern = '#(<div class="sacred">.*?</div>)(.*)#is';
if (preg_match_all($pattern, $message, $matches, PREG_SET_ORDER)) {
	
	$temp = preg_replace('#\b(?:(?:https?):\/\/|www\.)[-a-z0-9+&@\#\/%?=~_|!:,.;]*[-a-z0-9+&@\#\/%=~_|]#i', '<a href="$0" target="_blank">$0</a>', $matches[0][2]);
	
	$message = preg_replace('#'.$matches[0][2].'#', $temp, $message);
	
	echo $message;
	
}
?>

Here is a link to the php doc about preg_match_all, it could be interesting for you to know more about this function:

http://fr.php.net/manual/fr/function.preg-match-all.php

Include the <div>... pattern into the search pattern and replace it by itself.

<?php
$message = '<div class="sacred">[url]http://www.daniweb.com/[/url] is inside the div tag so I do not want it replaced.</div>[url]http://www.google.com/[/url] is outside the div tag so I do want it replaced';
$exclude = '<div class=\"sacred\">.*?<\/div>';
$pattern = '(https?\:\/\/.*?\..*?)(?=\s|$)';
$message= preg_replace("~(($exclude)?($pattern))~i", '$2<a href="$4" target="_blank">$5</a>$6', $message);
echo $message;
?>
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.