PHP Search and Replace question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ErickP
Forum Newbie
Posts: 2
Joined: Fri Apr 09, 2010 2:20 pm

PHP Search and Replace question

Post by ErickP »

Hi Everyone,

I'm currently using the "str_ireplace" function to replace some words in a text with something else. So far everything works fine. The problem I have is that within this text are html links and the replace function also replaces the words within the links. I do not want this.

Basically I would like to replace words within the text except for when this text lies between the < and > characters. I thought of using preg but I'm not sure how it would work with this also.

For example, in a sentence such as:

"The lamb lies <a href="?page=down">down</a> on broadway". I would like the word "down" shown as the link to be able to change to something else but not the "down" within the href itself.

Any geniuses out there to help me out?

Thanks,

Erick P.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: PHP Search and Replace question

Post by requinix »

The easiest way I've found is to split the text into alternating HTML and not-HTML parts.

Code: Select all

$string = "This string has <b>bold</b> and <i>italic</i> tags";
$parts = preg_split('/(<(?:[^>\'"]*|\'[^\']*\'|"[^"]*")*>)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
$html = false; foreach ($parts as &$part) {
	if (!$html) {
		// do whatever you want
		$part = str_replace("b", "6", $part);
	    	$part = str_replace("i", "!", $part);
	} else {
		// no nothing
	}
	$html = !$html;
}
$string = implode("", $parts);

echo $string;
ErickP
Forum Newbie
Posts: 2
Joined: Fri Apr 09, 2010 2:20 pm

Re: PHP Search and Replace question

Post by ErickP »

Looks very interesting tasairis. I'll give that a shot.

Thanks!

Erick P.
Post Reply