Link to home
Start Free TrialLog in
Avatar of Chris Andrews
Chris AndrewsFlag for United States of America

asked on

Need help with preg_replace script to change adsense ads from sync to async

I do adsense sharing on my site.  My users store their adsense code in my db.

I need to use the newer async adsense ads on the site, but some users have the old sync code saved in the db.

So my goal here is to take the string that contains the old sync code, remove the publisher id and slot number, and insert those into the async code, as the page is made.

Ok, I've got:

//-----------------------

$old_ad_code = '<script type="text/javascript">
    google_ad_client = "pub-id-1234567";  //need the string within the quotes
    google_ad_slot = "slot-123";  //need the string between the quotes
    google_ad_width = 468;
    google_ad_height = 60;
</script>
<!-- ap-sm-banner -->
<script type="text/javascript"
src="//pagead2.googlesyndication.com/pagead/show_ads.js">
</script>';

//-----------
//then need to insert those strings into the async code
//----------

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- ap-sm-banner -->
<ins class="adsbygoogle"
     style="display:inline-block;width:468px;height:60px"
     data-ad-client="insert-pub-id-string-here"  //pub string
     data-ad-slot="insert-ad-slot-string-here">  //slot string
</ins>  
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

//--------------------------


ok, suppose I could use explode on this?  

But it seems like preg_replace might be better?  But I have no idea how to use that really.

Can you show me how to do this?

Thanks,

Chris
Avatar of Ahmed Merghani
Ahmed Merghani
Flag of Sudan image

Hello,

Can you be more specific so we can advise regarding?
What do you want to convert for example "pub-id-1234567" to?
What do you want to convert for example "slot-123" to?
ASKER CERTIFIED SOLUTION
Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You could do it with a single preg_replace, but it's probably easier to understand (and thus maintain) when kept separate.
Avatar of Chris Andrews

ASKER

Awesome - thank you very much!