title: How can I extract all anchor tags, their hrefs and their anchor text within a string?
body: <p>I need to process links within an html string in several different ways.</p>
  
  <pre><code>$str = 'My long &lt;a href="http://example.com/abc" rel="link"&gt;string&lt;/a&gt; has any
          &lt;a href="/local/path" title="with attributes"&gt;number&lt;/a&gt; of
          &lt;a href="#anchor" data-attr="lots"&gt;links&lt;/a&gt;.'
  $links = extractLinks($str);
  foreach ($links as $link) {
      $pattern = "#((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\&lt;|$|\.\s)#ie";
      if (preg_match($pattern,$str)) {
          // Process Remote links
          //   For example, replace url with short url,
          //   or replace long anchor text with truncated
      } else {
          // Process Local Links, Anchors
  
      }
  }
  function extractLinks($str) {
      // First, I tried DomDocument
      $dom = new DomDocument();
      $dom-&gt;loadHTML($str);
      return $dom-&gt;getElementsByTagName('a');
      // But this just returns:
      //   DOMNodeList Object
      //   (
      //       [length] =&gt; 3
      //   )
  
      // Then I tried Regex
      if(preg_match_all("|&lt;a.*(?=href=\"([^\"]*)\")[^&gt;]*&gt;([^&lt;]*)&lt;/a&gt;|i", $str, $matches)) {
          print_r($matches);
      }
      // But this didn't work either.
  }
  </code></pre>
  
  <p>Desired result of <code>extractLinks($str)</code>:</p>
  
  <pre><code>[0] =&gt; Array(
             'str' = '&lt;a href="http://example.com/abc" rel="link"&gt;string&lt;/a&gt;',
             'href' = 'http://example.com/abc';
             'anchorText' = 'string'
         ),
  [1] =&gt; Array(
             'str' = '&lt;a href="/local/path" title="with attributes"&gt;number&lt;/a&gt;',
             'href' = '/local/path';
             'anchorText' = 'number'
         ),
  [2] =&gt; Array(
             'str' = '&lt;a href="#anchor" data-attr="lots"&gt;links&lt;/a&gt;',
             'href' = '#anchor';
             'anchorText' = 'links'
         );
  </code></pre>
  
  <p>I need all of these so I can do things like edit the href (add tracking, shorten, etc.), or replace the whole tag with something else (<code>&lt;a href="/u/username"&gt;username&lt;/a&gt;</code> could become <code>username</code>).</p>
  
  <p>Here's a <a href="https://eval.in/147831" rel="noreferrer">demo</a> of what I'm trying to do.</p>