获取 HREF 并使用 <a> PHP 丢弃原始标签



我正在使用wordpress,我使用的这个函数返回这个或类似这样的东西:

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

我想做的是从该标签中获取HREF并将其存储在变量中,这样我就可以轻松地操作它。然后,在我有了HREF信息后,我想放弃<li><a>标签。

我查看了php函数strip_tag(),这并没有做我想要的。

如果这是过于复杂,我将只是不包括在网页的工作,但如果它可以做到…

首先,确保不存在返回未格式化数据的其他函数。

如果没有,这里有一个快速而肮脏的正则表达式来提取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];

您的解决方案将看起来像这样。

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

更多示例:http://php.net/manual/en/function.preg-match.php

来点实际操作怎么样?——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有很多内置函数。您可能可以获得图像URL本身,而不必从代码中破解它。http://codex.wordpress.org/Function_Reference/wp_get_attachment_image_src

如果你知道附件id,这将返回url

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

最新更新