Jason Eyebe
Jason Eyebe

Reputation: 161

Preg Replace Remove Trailing Space on Output

I am using preg_replace to generate contextual links in text blocks using the following code:

$contextualLinkStr = 'mytext';

$content = 'My text string which includes MYTEXT in various cases such as Mytext and mytext. However it also includes image tags such as <img src="http://www.myurl.com/mytext-1.jpg">';

$content = preg_replace('/' . $contextualLinkStr . '/i ', '<a href="foo.html">\\0</a>', $content);

I have a trailing space in my preg_replace in my search pattern. This is because I want the function to ignore any instances of mytext that appear in image links. This works but causes a problem with the output. The output also carries the trailing space as follows:

<a href="foo.html">mytext </a>

So my question is - How do I remove the trailing space from within the link on the output and then add a trailing space after the link to account for the already removed space. I need the output to be as follows:

<a href="foo.html">mytext</a>_

Where "_" is the trailing space. Can anybody please help?

Thanks,

Jason.

Upvotes: 1

Views: 98

Answers (1)

zx81
zx81

Reputation: 41848

To ignore image links, use (*SKIP)(*F)

To ignore mytext in image links, don't introduce a space when you are matching. Instead, use this regex to ignore image links direcly:

(?i)<img[^>]*>(*SKIP)(*F)|mytext

See demo.

The left side of the alternation | matches complete <img links> then deliberately fails, after which the engine skips to the next position in the string. The right side matches mytext, and we know they are the right ones because they were not matched by the expression on the left.

Using this, you can do a straight preg_replace:

$regex = "~(?i)<img[^>]*>(*SKIP)(*F)|" . $contextualLinkStr . "~";
$replaced = preg_replace($regex,'<a href="foo.html">$0</a>',$content);

For full details on this exclusion technique and its many applications, see the question and article in the reference.

Reference

Upvotes: 1

Related Questions