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.
PHP Search and Replace question
Moderator: General Moderators
Re: PHP Search and Replace question
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;Re: PHP Search and Replace question
Looks very interesting tasairis. I'll give that a shot.
Thanks!
Erick P.
Thanks!
Erick P.