Im getting Html string to a variable, and I want to get only the href from the a tag php

Viewed 20

hey Im using woocommerce and this is what i tried to do:

function fu() {
$orders = wc_get_orders( array('numberposts' => -1) );
foreach( $orders as $order ){
    foreach ( $order->get_items() as $item_id => $item ) {
        $item_data = $item->get_data();
        $item_meta_data = $item->get_meta_data();
        $formatted_meta_data = $item->get_formatted_meta_data( '_', true );
        $item_meta_data = $item->get_meta_data();
        foreach($item_meta_data as $meta_data_item) {
            if (str_contains($meta_data_item->key, 'Uploaded File')){
                echo $meta_data_item->value;
            }
        
        }

   }

} } add_shortcode('fu', 'fu');

the point is that

echo $meta_data_item->value;

this line return a string:

<a href="http://sneakerscheck.co.il/wp-content/uploads/1663774829-WhatsApp-Image-2022-09-21-at-12.25.06.jpeg" class="fme_thankyou_page1" target="_blank" typee="application/" "="">Preview Image</a>
<a href="http://sneakerscheck.co.il/wp-content/uploads/1663774829-WhatsApp-Image-2022-09-21-at-12.25.06.jpeg" download=""><button class="btn fme_download ffff" style="padding:7px;border:none;cursor:pointer;margin-left:10px;"><i class="fa fa-download"></i>Download</button></a>

and i want to get the first href from the first a tag only with php how can i do it sorry for my english

1 Answers

strpos, strlen, substr. Not in that order.

$str = '<a href="http://sneakerscheck.co.il/wp-content/uploads/1663774829-WhatsApp-Image-2022-09-21-at-12.25.06.jpeg" class="fme_thankyou_page1" target="_blank" typee="application/" "="">Preview Image</a>
<a href="http://sneakerscheck.co.il/wp-content/uploads/1663774829-WhatsApp-Image-2022-09-21-at-12.25.06.jpeg" download=""><button class="btn fme_download ffff" style="padding:7px;border:none;cursor:pointer;margin-left:10px;"><i class="fa fa-download"></i>Download</button></a>';
$open = "href=\"";
$close = "\"";
$start_pos = strpos($str, $open) + strlen($open);

echo substr($str, $start_pos, strpos($str, $close, $start_pos) - $start_pos);

will print:

http://sneakerscheck.co.il/wp-content/uploads/1663774829-WhatsApp-Image-2022-09-21-at-12.25.06.jpeg
Related