Skip to content

Instantly share code, notes, and snippets.

@borndangerous
Created April 19, 2011 18:22
Show Gist options
  • Save borndangerous/929148 to your computer and use it in GitHub Desktop.
Save borndangerous/929148 to your computer and use it in GitHub Desktop.

Here's the deal: I accidentally did a mass find/replace across an entire MySQL table. Specifically, the table containing hundreds of Wordpress posts & pages (wp_posts).

"D'oh" doesn't even begin to explain the moment after that fateful click. For the record, I blame poor user interface design. Here's a screenshot of what happened:

Consequently, this ruined all my Wordpress posts containing shortcodes (i.e: all of them). For instance...

[my_shortcode]Hello world.[/my_shortcode]
[my_image_shortcode]http://mydomain.com/image.png[/my_image_shortcode]

is now

[my_shortcode]Hello world.my_shortcode]
[my_image_shortcode]http://mydomain.com/image.pngmy_image_shortcode]

You can see how this would be a pain in the ass to fix across a few hundred posts/pages, totaling 160,000+ words of content.

I have a new plugin called "Regex Search" that allows me to do mass regex-based find/replace functions. I just need to figure out the Regex that does this:

Find all instances of my_shortcode] where the character preceding my_shortcode is NOT /. Add a [/ between the character that is NOT a / and my_shortcode].

So this would find:

[my_shortcode]Hello world.my_shortcode]

and replace it with:

[my_shortcode]Hello world.[/my_shortcode]

I'll stop here, since I realize this might be madly confusing already. I can explain further to anyone that thinks that may be able to solve this mess.

David

http://twitter.com/dvdwlsh

@isaacdudek
Copy link

Written for/with Ruby. Probably easily adaptable for use with your Regex Search plugin.

>> string
=> "asdf asdf [my_shortcode]Hello world.my_shortcode] asdf asdf [some_other_shortcode] hey now some_other_shortcode][my_shortcode]Hello world.my_shortcode]\n[my_image_shortcode]http://mydomain.com/image.pngmy_image_shortcode]\n"
>> string.gsub(/\[(\w+)\](.*?)(\1\])/m, '[\1]\2[/\3')
=> "asdf asdf [my_shortcode]Hello world.[/my_shortcode] asdf asdf [some_other_shortcode] hey now [/some_other_shortcode][my_shortcode]Hello world.[/my_shortcode]\n[my_image_shortcode]http://mydomain.com/image.png[/my_image_shortcode]\n"

Seems to work for me. Backup your database before running, caveat emptor, etc.

Hit me up if you're interested in how this works.

http://twitter.com/isaacdudek

@borndangerous
Copy link
Author

Issac, seriously, you saved me a massive amount of work, and managed to teach me a hell of a lot about regex along the way. I was able to use, adapt, and tweak your patterns to completely repair everything that got messed up. Huge, huge, huge help. THANK YOU. If I can do anything to repay the favor, let me know.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment