Ashish Jangra
Ashish Jangra

Reputation: 63

Replace text in a string exclude anchor text

I would like to search words in string and want to replace first occurrence in that string. Also i would like to exclude text which is between Tag only. Which means text which has hyper link should not be replace.

This should check new line in new line.

Example:

Here is < a > my < / a > String. I Would like to replace my string. In this string only 1 my will be replace which is first and doesn't has anchor link.

Replace my with "This"

Output.

Here is < a > my < / a > String. I would like to replace this string. In this string only 1 my will be replace which is first and doesn't has anchor link.

Thanks

Upvotes: 1

Views: 526

Answers (1)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You can use this regex to match the first occurrence of "my" which is not contained in <a> </a> tag only.

^.*?\Kmy(?![^>]*\/\s*a\s*>)

and replace it with "this" as you want in your post.

Explanation:

  • ^ --> Start of input
  • .*? --> Match any characters in non-greedy way (to capture first occurencce of my)
  • \K --> Reset whatever matched so only "my" gets matched which needs to be replace by "this"
  • (?![^>]*\/\s*a\s*>) --> Negative look ahead to ensure "my" text is not contained in <a> </a> tag.

Demo

Here is a sample PHP code for same,

$str = 'Here is < a > my < / a > String. I Would like to replace my string. In this string only 1 my will be replace which is first and doesn\'t has anchor link.';
$res = preg_replace('/^.*?\Kmy(?![^>]*\/\s*a\s*>)/','this',$str);
echo $res;

This gives following output like you expect,

Here is < a > my < / a > String. I Would like to replace this string. In this string only 1 my will be replace which is first and doesn't has anchor link.

Upvotes: 1

Related Questions