开发者

Grab the HREF and discard of that original <a> tag with PHP

Im working with wordpress and this function im using returns this or something that looks like this:

<li><a href="http://foo.com/wp-content/uploads/2011/07/picture.png">picture</a></li>

What Im trying to do is get the HREF from that tag and store it in a variable, so I can manipulate it easily. Then after i have the HREF info i want to discard of the <li> and the <a> tag.

I looked into the php function strip_tag() and that doesn't do what i want.

If this is overly complicated i will just not include the work in the webpage, but if it can be 开发者_如何转开发done.. help would be great.


First of all, make sure no other function exists that returns the unformatted data.

If not, here's a quick and dirty regex to pull out the URL:

$str = '<li><a href="http://foo.com/wp-content/uploads/2011/07/picture.png">picture</a></li>';

preg_match('~\shref="([^"]++)"~', $str, $matches);
$url = $matches[1];


Your solution will look something like this.

preg_match('@<a href="(.*?)"@i', $your_string_here, $matches);
$the_url = $matches[1];

More examples here: http://php.net/manual/en/function.preg-match.php


How about something more hands on? - http://wp-snippets.com/727/custom-display-of-links-blogroll/

    $links = $wpdb->get_results("SELECT * FROM $wpdb->links ORDER BY link_name ASC");
    //start going through all the links and get the required values for each link
    foreach ($links as $link) {
      $linkurl=$link->link_url;
      $linkdesc=$link->link_description;
      $linkname=$link->link_name;
      $linkimage=$link->link_image;
      $linknotes=$link->link_notes; }

Wordpress has many built in functions. You can probably get the image URL itself without having to hack it out of the code.

http://codex.wordpress.org/Function_Reference/wp_get_attachment_image_src

This will return the url if you know the attachment id

$imgData = wp_get_attachment_image_src( $attachment_id);
echo $imgData[0];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜