$re = '/(<span\b[^"]+class="TagsStyle"[^>]*>|(?!\A)\G)([^,<]+)(,?\s*)/';
$str = '<div align="center">
<span class="CatTStyle">Category:</span>
<span class="CatStyle">PHYSIOTHERAPY</span>
<br>
<br>
<span class="BusTStyle">Business Name:</span>
<span class="BusStyle">Physio</span>
<br>
<span class="PhTStyle">Phone:</span>
<span class="PhStyle"><a onclick="_gaq.push([\'_trackEvent\', \'Phone\', \'Click to Call\', document.title])" href="tel:555 5555">555 5555 <img src="img/call.png"></a></span>
<br>
<span class="AddrTStyle">Address:</span>
<span class="AddrStyle">1 Street Rd, Town, Country</span>
<br>
<span class="EmlTStyle">Email:</span>
<span class="EmlStyle"><a onclick="_gaq.push([\'_trackEvent\', \'Email\', \'Click to Email\', document.title])" href="mailto:email@email.com">email@email.com</a></span>
<br>
<br>
<span class="WsTStyle">Website:</span>
<span class="WsStyle"><a onclick="_gaq.push([\'_trackEvent\', \'Website\', \'Click to Website\', document.title])" href="http://www.webiste.com">www.website.com</a></span>
<br>
<br>
<span class="TagsTStyle">PRODUCTS / SERVICES:</span>
<span class="TagsStyle">PHYSIOTHERAPY, BACK PAIN, SPINE INJURY</span>
<br>
</div>
<script async type="text/javascript">
if ($(window).width() > 800) {document.write("</td><td align=\'center\' valign=\'top\' width=\'350\'>");}
if ($(window).width() < 800) {document.write("</td></tr><tr><td align=\'center\' valign=\'top\' width=\'350\'>");}
</script>
<br>
<div id="map" align="left" style="text-align:left;"></div>
<script type="text/javascript">
var address=\'1 Street Rd, Town, Country\';
var map = new google.maps.Map(document.getElementById(\'map\'), {
mapTypeId: google.maps.MapTypeId.TERRAIN,
zoom: 15
});
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
\'address\': address
},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
map.setCenter(results[0].geometry.location);
}
});
</script>
';
$subst = "\1<a href=\"../search.php?searchQuery=\2\">\2</a>\3";
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php