Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can achieve this by using <code>preg_replace</code>, 2 patterns and two replacememts:</p> <pre><code>&lt;?php $add = "utm=some&amp;medium=stuff"; $patterns = array( '/(https?:\/\/(?:www)?me\.com(?=.*?\?)[^"]*)/', # positive lookahead to check if there is a ? mark in url '/(https?:\/\/(?:www)?me\.com(?!.*?\?)[^"]*)/' # negative lookahead to check if ? mark is not in ); $replacements = array( "$1&amp;".$add, # replacement if first pattern take place '$1?'.$add # replacement if second pattern take place ); $str = 'Lorem ipsum &lt;a href="http://www.me.com"&gt;dolor sit&lt;/a&gt; amet, &lt;a href="http://www.me.com/page.php?id=10"&gt;consectetur&lt;/a&gt; elit.'; $str = preg_replace($patterns, $replacements, $str); echo $str; /* Output: Lorem ipsum &lt;a href="http://www.me.com&amp;utm=some&amp;medium=stuff"&gt;dolor sit&lt;/a&gt; amet, &lt;a href="http://www.me.com/page.php?id=10&amp;utm=some&amp;medium=stuff"&gt;consectetur&lt;/a&gt; elit. */ ?&gt; </code></pre> <p>I liked others answers using DOM-solutions, then I tested the time each snippet takes for the following input:</p> <pre><code>&lt;a href="http://www.me.com"&gt;Lorem&lt;/a&gt; &lt;a href="http://www.me.com/"&gt;ipsum&lt;/a&gt; &lt;a href="http://www.me.com/#section-2"&gt;dolor&lt;/a&gt; &lt;a href="http://www.me.com/path-to-somewhere/file.php"&gt;sit&lt;/a&gt; &lt;a href="http://www.me.com/?"&gt;amet&lt;/a&gt;, &lt;a href="http://www.me.com/?foo=bar"&gt;consectetur&lt;/a&gt; &lt;a href="http://www.me.com/?foo=bar#section-3"&gt;elit&lt;/a&gt;. </code></pre> <p>With <code>microtime</code>:</p> <pre><code>$ts = microtime(true); // codes printf("%.10f\n", microtime(true) - $ts); </code></pre> <p>That you can see them below (ms):</p> <pre><code>@squeamish ossifrage: 0.0001089573 @Cobra_Fast: 0.0003509521 @Emissary: 0.0094890594 @Me: 0.0000669956 </code></pre> <p>That was interesting to me, <code>RegEx</code>es done well.</p>
 

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