0

I'm trying to replace the keyword "site" with "Stack Overflow" in the source string, but it should only replace when the keyword is not inside a HTML <a> tag or between <a> and </a>.

I've searched a lot and unfortunately haven't found a solution yet.

What I want:

Right now, site is available at <a href="http://www.example.com/site">site.com</a>

...should replace to...

Right now, Stack Overflow is available at <a href="http://www.example.com/site">site.com</a>

Unihedron
  • 10,902
  • 13
  • 62
  • 72
Mad Marvin
  • 3,309
  • 3
  • 18
  • 18

2 Answers2

4

Use (*SKIP)(*FAIL) technique

Use a regex replacement:

/<a.*?<\/a>(*SKIP)(*F)|site/

Replace to:

Stack Overflow

Explanation:

/<a.*?<\/a>   # Matches entire <a> tags
  (*SKIP)(*F) # Bumps to the next position and forces match to fail
 |            # Allows alternation if the first condition does not get matched
  site        # literal character sequence "site"
/x

Online Regex Demo

Community
  • 1
  • 1
Unihedron
  • 10,902
  • 13
  • 62
  • 72
1

If the <a> tag is always going to be to the right of your text then some parsing and replacing will do the trick. This will split your string into two strings, replace site in the first string, and then put the pieces back together.

$string = 'Right now, site is available at <a href="http://www.example.com/site">site.com</a>';
$find   = '<a';
$position = strpos($string, $find);

$strlen = strlen($string);
$string_1 = substr($string, 0, $position);
$string_2 = substr($string, $position,  $strlen); 

$replace_string = str_replace('site','Stack Overflow', $string_1);

$final_string = $replace_string.$string_2;

echo $final_string;

Result: Right now, Stack Overflow is available at <a href="http://www.example.com/site">site.com</a>

Dan
  • 9,391
  • 5
  • 41
  • 73
  • Nice practical answer, but it is unfortunate to have the constraint of having the tag to the right. With regex this can be worked with without this constraint, at a slight cost of efficiency. – Unihedron Jul 26 '14 at 15:15
  • I agree...however I don't like regex :) – Dan Jul 26 '14 at 15:15
  • Thanks @Dan - however the tags are automatically generated depending on the content, which means they could appear anywhere. Appreciate your effort, nonetheless! – Mad Marvin Jul 26 '14 at 15:46