Publicus
Publicus

Reputation: 1548

Using str_replace only if conditions are met

I'm doing str_replace on a variable containing a HTML string. The aim is to add "data-rel="external" target="_blank"" to all the a-href's.

$html = str_replace("<a href=", "<a data-rel=\"external\" target=\"_blank\" href=", $html);

It works fine, but here's the challenge: If the original a-href is a a-href="mailto:[..], then it should add "data-rel="external" target="_system"".

Example:

<a href="http://apache.org">Link 1</a>

should become:

<a data-rel="external" target="_blank" href="http://apache.org">Link 1</a>

And

<a href="mailto:[email protected]">Link 2</a>

should become:

<a data-rel="external" target="_system" href="mailto:[email protected]">Link 2</a>

Any ideas how to solve this?

Upvotes: 1

Views: 364

Answers (4)

dt192
dt192

Reputation: 1013

This worked for me

<?php
$html='<a href="http://apache.org">Link 1</a><a href="mailto:[email protected]">Link 2</a>';
$html = str_replace('<a href="mailto', '<a data-rel="external" target="_system" href="mailto', $html);
$html = str_replace('<a href=', '<a data-rel="external" target="_blank" href=', $html);
echo $html;
?>

or this

<?php
$html='<a href="http://apache.org">Link 1</a><a href="mailto:[email protected]">Link 2</a>';
$html = str_replace(array('<a href="mailto','<a href='), array('<a data-rel="external" target="_system" href="mailto','<a data-rel="external" target="_blank" href='), $html);
echo $html;
?>

output

<a data-rel="external" target="_blank" href="http://apache.org">Link 1</a>
<a data-rel="external" target="_system" href="mailto:[email protected]">Link 2</a>

Upvotes: 0

RelevantUsername
RelevantUsername

Reputation: 1340

In other cases where you couldn't use str_replace, preg_replace might become handy :

preg_replace('/<a href="mailto/', '<a data-rel="external" target="_system" href="mailto', $html);

Upvotes: 0

Glitch Desire
Glitch Desire

Reputation: 15043

Run a mailto str_replace first,

$html = str_replace("<a href=\"mailto:", 
    "<a data-rel=\"external\" target=\"_system\" href=\"mailto:", $html);

After this has executed, these will no longer be affected by a str_replace looking for <a href because they will be <a data-rel.

Upvotes: 3

Scott Cranfill
Scott Cranfill

Reputation: 1054

I would test for the appearance of the substring "mailto:" within $html, and run different str_replace commands depending on whether or not that is true.

Upvotes: 0

Related Questions