nhalink
nhalink

Reputation: 513

split link string

I have a link that looks like this:
<a href="/site/cdb/index.php?adinfo=272">Company Inc.</a>

I want to split it so I remain with two pieces of information, the value of adinfo, in the example 272, and the linking words, in the example Company Inc..

I can do it with the code below but that is six lines of code which chops the string in to bits and I find it quite ugly, so I was wondering if there is an easier/nicer way.

$str = right($str, strlen($str)-36);
$pos = strpos($str, '"');
$value = left($str, $pos);
$str = right($str, strlen($str)-($pos+2));
$pos = strpos($str, '</a>');
$link = left($str, $pos);

(left and right are functions of my own that keep the left or right part of a string and cut of the rest)

Upvotes: 0

Views: 503

Answers (3)

CFL_Jeff
CFL_Jeff

Reputation: 2719

If you don't want to bother with regular expressions:

Use strpos() to find the position of the substring "?adinfo=" and you will have the relative location of that url parameter's value.

Use strpos() again to find the first occurence of ">" and you will have the location of the beginning of the link text.

Upvotes: 0

bos
bos

Reputation: 6535

php > $s = '<a href="/site/cdb/index.php?adinfo=272">Company Inc.</a>';
php > echo preg_replace('@.*adinfo=(\d+).*?>(.*?)</a>@', '$1 - $2', $s);
272 - Company Inc.

Upvotes: 0

Aleks G
Aleks G

Reputation: 57306

You shouldn't do things like that with find/replace/regex but try using DOM for HTML parsing. However if you're set on just manipulating the string, then you can easily achieve this with a simple regex:

$str = '<a href="/site/cdb/index.php?adinfo=272">Company Inc.</a>';

$matches = array();
preg_match('/<a href=\"[^\?]+\?adinfo=(272)\">([^<]+)/', $str, $matches);

$id = $matches[1];
$name = $matches[2];

Upvotes: 2

Related Questions