How to Reuse Strings in WordPress 'Search Regex' Replacements
I had a hard time figuring out how to reuse strings when doing replacements with the WordPress 'Search Regex' plugin, but after some research, I finally got it to work.
Almost no sites explain this, and the one site I did find had misinformation. The official Search Regex documentation doesn't mention it either. I wondered if it used the same syntax as PHP, tested it out, and it worked, so I'm writing it down as a note. Does nobody else use this? Is PHP syntax just common knowledge? Maybe I struggled because I'm too used to regex replacements using `query-replace-regexp` in Emacs.
Once you know how, it's simple. In Emacs, you wrap patterns in `( ~~~~ )` and reuse them with `1`, where `` acts as the special escape key.
In PHP and the WordPress 'Search Regex' plugin, you don't need the ``. You just wrap them in `( ~~~~ )`. (Though you might need to escape literal parentheses like `(` if you're matching them). To reuse the captured group, you use `$1`.
For example:
<a href="https://www.facebook.*>~~~~~<img src="http~~~~/></a> みたいなのを前後の<a ~> </a>を除いて真ん中の <img src="http~~~~/> だけを残したいとき、 検索:<a href="https://www.facebook.*>(<img .*/>)</a> 置換:$1 とする。

Something like this.
This is super convenient—even if you leave the replacement field blank, running a search lets you find specific articles and text.

Furthermore, if you put `$1` in the replacement field, it will output the matched text as-is.

What is the practical use case for this? You can copy text and images from past Facebook posts directly in your browser, paste them into a new WordPress post, and easily build a nice-looking article. However, the images will still be hosted on Facebook, meaning clicking them takes users back to Facebook. Removing those links is the first step of the cleanup process. The images look fine as they are for now, but eventually, I'll upload them to the media library and use Search Regex to replace those URLs too!


