Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you'd like to abstract all the nasty parsing away from your script you can always use a <a href="http://en.wikipedia.org/wiki/Document_Object_Model" rel="nofollow noreferrer">DOM</a> parser of which there are <a href="https://stackoverflow.com/a/3577662/1238344">many available</a>. For this example I've opted for <a href="http://simplehtmldom.sourceforge.net/" rel="nofollow noreferrer">Simple HTML-DOM</a> as It's the only one I'm actually familiar with (it's admittedly not the most efficient library but you aren't doing anything intensive).</p> <pre><code>include 'simple_html_dom.php'; $html = str_get_html($htmlString); foreach($html-&gt;find('a') as $a){ $url = strtolower($a-&gt;href); if( strpos($url, 'http://me.com') === 0 || strpos($url, 'http://www.me.com') === 0 || strpos($url, 'http://') !== 0 // local url ){ $url = explode('?', $url, 2); if(count($url)&lt;2) $qry = array(); else parse_str($url[1], $qry); $qry = array_merge($qry, array( 'utm' =&gt; 'some', 'medium' =&gt; 'stuff' )); $parts = array(); foreach($qry as $key =&gt; $val) $parts[] = "{$key}={$val}"; $a-&gt;href = sprintf("%s?%s", $url[0], implode('&amp;', $parts)); } } echo $html; </code></pre> <p>In this example I've assumed that <em>me.com</em> is your website and that local paths should also qualify. I am also assuming that query strings are likely to be simple <em>key:value</em> pairs. In it's current form, if a URL already has one of your query parameters then it is over-written. If you'd like to retain the existing values then you will need to swap the order of the parameters in the <code>array_merge</code> function.</p> <h2>input:</h2> <pre><code>&lt;a href="http://me.com/"&gt;test&lt;/a&gt; &lt;a href="http://WWW.me.com/"&gt;test&lt;/a&gt; &lt;a href="local.me.com.php"&gt;test&lt;/a&gt; &lt;a href="http://notme.com"&gt;test&lt;/a&gt; http://me.com/not-a-link &lt;a href="http://me.com/?id=10&amp;utm=bla"&gt;test&lt;/a&gt; </code></pre> <h2>output:</h2> <pre><code>&lt;a href="http://me.com/?utm=some&amp;medium=stuff"&gt;test&lt;/a&gt; &lt;a href="http://www.me.com/?utm=some&amp;medium=stuff"&gt;test&lt;/a&gt; &lt;a href="local.me.com.php?utm=some&amp;medium=stuff"&gt;test&lt;/a&gt; &lt;a href="http://notme.com"&gt;test&lt;/a&gt; http://me.com/not-a-link &lt;a href="http://me.com/?id=10&amp;utm=some&amp;medium=stuff"&gt;test&lt;/a&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload