user1222589
user1222589

Reputation: 87

about use regex to convert url to link

I need to convert the url in the article to the 3g domain.

for example, i need to convert

here is the link:http://www.mydomain.com/index thanks

to

here is the link:<a href='http://3g.mydomain.com$4' target='_self'>http://3g.$3.com$4</a> thanks

don't convert the other domain, just mydomain. here is the code:

$c = "/([^'\"=])?http:\/\/([^ ]+?)(mydomain)\.com([A-Za-z0-9&%\?=\/\-\._#]*)/";
$b=preg_replace($c, "$1<a href='http://3g.$3.com$4' target='_self'>http://3g.$3.com$4</a>",$b);

it works very well,but if the text like this:

<a href="http://www.mydomain.com/44" target="_blank" class="blue">a link</a>

it will return the wrong result like this:

<a href="<a href='http://3g.mydomail.com/44' target='_self'>http://3g.mydomain.com/44</a>" target="_blank" class="blue">a link</a>

but l need the result of

<a href="http://3g.mydomain.com/44" target="_blank" class="blue">a link</a>

how should i do?

Upvotes: 0

Views: 110

Answers (2)

staafl
staafl

Reputation: 3225

You should do the following:

  1. Strip target attributes from existing hyperlinks
  2. Rewrite hyperlinks in href attributes
  3. Rewrite any other hyperlinks

    $plain = "http://([^ ]+?)(mydomain)\.com(/?[^'\"\s]*(?=['\"\s]))";

    $plain_replace = "http://3g.$3.com$4";

    $in_href = "href=(['\"])" + plain + "(['\"])";

    $in_href_replace = "href='http://3g.$3.com$4' target='self'";

    $strip_target = "target=['\"][^'\"]*['\"]";

    ...

So:

  1. Replace $strip_target with ""

  2. Replace $in_href with $in_href_replace

  3. Replace $plain with $plain_replace

(The regexes are tested to work in C#, you might have to adjust the \ escaping to suit the php regex rules.)

Upvotes: 1

Brett Zamir
Brett Zamir

Reputation: 14345

Get rid of the first ? in your regular expression. That allows for the absence of a preceding character.

Or, perhaps more to your intention, if you want to allow URLs at the beginning, you can replace:

([^'\"=])?

with:

(^|[^'\"=])

...which will allow a link if at the very beginning, or if not preceded by a quote, etc., but not otherwise.

Upvotes: 0

Related Questions