Pierce McGeough
Pierce McGeough

Reputation: 3086

Use regex to extract link

I have particular lines that will appear in a post from a textarea and I need to extract them and convert them to a link. The php code i had from a previous example works ok if the id is just a digit, but I now need it to work for a url that could contain letters, numbers, dashes and forward slashed

$pattern = '/@\[([^\]]+)\]\(id:(\d+)\)/';
$replacement = '<a href="link/$2">$1</a>';
$text = preg_replace($pattern, $replacement, $text);

The pattern matches everything except the url. How do I change \d+ to what I need. I thought \w might have worked but it doesnt.

@[Lucy Lawless](id:residential-lettings/landlords/view/landlord/161) will become <a href="residential-lettings/landlords/view/landlord/161">Lucy Lawless</a>

@[200 Daly Park ](id:residential-lettings/properties/view/property/257) will become <a href="residential-lettings/properties/view/property/257">200 Daly Park</a>

@[Courrrty](id:residential-lettings/supplier/view/supplier/7) will become <a href="residential-lettings/supplier/view/supplier/7">Courrrty</a>

Upvotes: 0

Views: 98

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174844

Change your regex like below,

@\[([^\[\]]+)\]\(id:([^()]*)\)

and then replace the match with <a href="$2">$1</a>

DEMO

[^()]* Matches any character but not of ( or ) zero or more times.

$pattern = '~@\[([^\[\]]+)\]\(id:([^()]*)\)~';
$replacement = '<a href="$2">$1</a>';
$text = preg_replace($pattern, $replacement, $text);

Upvotes: 1

vks
vks

Reputation: 67988

\[([^\]]+)\]\(id:(.*?\d+)\)

Try this.See demo.Replace by <a href="link/$2">$1</a>.

Just changed \d+ to .*?\d+ so that it includes all upto \d+.

See demo.

http://regex101.com/r/tF4jD3/12

$re = "/\\[([^\\]]+)\\]\\(id:(.*?\\d+)\\)/m";
$str = "[Lucy Lawless](id:residential-lettings/landlords/view/landlord/161)\n[200 Daly Park ](id:residential-lettings/properties/view/property/257)";
$subst = "<a href=\"link/$2\">$1</a>";

$result = preg_replace($re, $subst, $str);

Upvotes: 0

Related Questions